Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values to a Scipy sparse matrix with indexes and values

I'm working in a program for Power System analysis and I need to work with sparse matrices.

There is a routine where I fill a sparse matrix just with the following call:

self.A = bsr_matrix((val, (row,col)), shape=(nele, nbus), dtype=complex)

As this matrix won't change over time. Yet another matrix does change over time and I need to update it. Is there a way that having, for example:

co     = [ 2, 3, 6]
row    = [ 5, 5, 5]
val    = [ 0.1 + 0.1j, 0.1 - 0.2j, 0.1 - 0.4j]

I can add those to a previously initialized sparse matrix? How would be the more pythonic way to do it?

Thank you

like image 814
amalbe Avatar asked Jul 18 '13 01:07

amalbe


1 Answers

You should use a coo_matrix instead, where you can change the attributes col, row and data of a previously created sparse matrix:

from scipy.sparse import coo_matrix
nele=30
nbus=40
col    = [ 2, 3, 6]
row    = [ 5, 5, 5]
val    = [ 0.1 + 0.1j, 0.1 - 0.2j, 0.1 - 0.4j]
test = coo_matrix((val, (row,col)), shape=(nele, nbus), dtype=complex)

print test.col
#[2 3 6]
print test.row
#[5 5 5]
print test.data
#[ 0.1+0.1j  0.1-0.2j  0.1-0.4j]
like image 67
Saullo G. P. Castro Avatar answered Oct 08 '22 00:10

Saullo G. P. Castro