0

So I am trying to copy values from one numpy array into a sparse matrix. The first array looks like this:

results_array = [[  3.00000000e+00   1.00000000e+00   4.00000000e+00   1.00000000e+03]
[  6.00000000e+00   2.00000000e+00   5.00000000e+00   7.00000000e+02]
[  1.60000000e+01   4.00000000e+00   8.00000000e+00   1.00000000e+03]}

The second value (or results_array[i][1]) dictates the column id, the third value (results_array[i][2]) dictates the row id and the fourth value (results_array[i][3]) dictates the value of that row, column pair.

So far what I have is this:

for i in result_array:
sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14))
print "last array", sparse_matrix

The output I get is:

File "C:/Users/Andrew/Google Drive/Uni/Final Year/Research Project/Programming/Mine/First UEA/xl_optim/Runestone 2.py", line 13, in <module>
sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14))
File "C:\Users\Andrew\Anaconda2\lib\site-packages\scipy\sparse\compressed.py", line 48, in __init__
other = self.__class__(coo_matrix(arg1, shape=shape))
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 182, in __init__
self._check()
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 219, in _check
nnz = self.nnz
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 194, in getnnz
nnz = len(self.data)
TypeError: len() of unsized object

I think I need to create the sparse matrix first and then add the values to it iteratively (I'm imagining something like a .append but to a specific location in the matrix) but I have no idea how to create an empty sparse matrix and then assign values to it.

Let me know if you need further clarification. Thanks!

1 Answer 1

4

The first element in the tuple you pass to csc_matrix needs to be a vector of values, whereas you are passing it an integer. More fundamentally, you're trying to call the csc_matrix constructor multiple times in a loop so that it would overwrite sparse_matrix on each iteration.

You want to call csc_matrix once with a vector for each parameter, like this:

values = results_array[:, 3]
row_idx = results_array[:, 2]
col_idx = results_array[:, 1]

sparse_array = csc_matrix((values, (row_idx, col_idx)), shape=(14, 14))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.