Python create an empty sparse matrix

Viewed 9060

I am trying to parse some real data into a .mat object to be loaded in my script.

I am getting this error:

TypeError: 'coo_matrix' object does not support item assignment

I found coo_matrix. However, I am not able to assign values to it.

data.txt

10 45
11 12 
4 1

I would like to get a sparse matrix of size 100x100. And to assign 1's to

Mat(10, 45) = 1
Mat(11, 12) = 1
Mat(4, 1) = 1

CODE

import numpy as np
from scipy.sparse import coo_matrix

def pdata(pathToFile):
    M = coo_matrix(100, 100)
    with open(pathToFile) as f:
        for line in f:
            s = line.split()
            x, y = [int(v) for v in s]
            M[x, y] = 1     
    return M

if __name__ == "__main__":
    M = pdata('small.txt')  

Any suggestions please ?

2 Answers
Related