[SciPy-user] Sparse matrix questions
Ed Schofield
schofield at ftw.at
Tue Feb 14 06:33:21 CST 2006
Nils Wagner wrote:
>from scipy.sparse import *
>from scipy import *
>
>A = rand(4,4)
>sparseA = csc_matrix(A)
>#
># How can I build the norm of a sparse matrix without using todense ?
>#
>eps = linalg.norm(sparseA.todense())
>
>
This is a non-trivial problem, and I don't think we have a function for
it. Could you write one and contribute it? ;)
># How do I scale a sparse matrix object ?
>#
>#sparseA = sparseA/0.5 # doesn't work
>
>
>
Interesting. I'll fix this in SVN. For now, just use multiplication
instead:
>>> sparseA *= 2.0
># How do I initialize a sparse matrix of order n \times m with zeros
>#
>B = zeros((4,5),Float)
>#sparseB = csc_matrix(B) # doesn't work
>
>
It's filled with zeros already. Just use
>>> sparseB = csc_matrix((4,5))
But for efficiency I suggest you use dok_matrix to construct and
manipulate matrices, then convert to csc or csr for solvers or matrix
multiplication.
For diagonals, you can use dok_matrix.setdiag():
>>> sparseB = dok_matrix((5,5))
>>> sparseB.setdiag([1]*5)
>>> sparseB.todense()
array([[ 1., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 1.]])
I hope this helps. In the future, please post questions like these on
the scipy-user list, not on scipy-dev :)
-- Ed
More information about the SciPy-user
mailing list