TheRealFakeNews
TheRealFakeNews

Reputation: 8183

Manipulating sparse matrices in Matlab

Suppose I have a sparse matrix Sparstica that is a vertical concatenation of several other sparse matrices. When I type Sparstica(:), I get a list of the nonzero elements. In the left column, will be the index of the element, in the right column will be the nonzero element.

How can I manipulate the i-th and j-th non-zero element of every other sparse block matrix in the middle n-2 blocks (n sparse block matrices in total)?


Appended: To clarify what I mean by the i-th and j-th element of every other sparse matrix, suppose I have

Sparstica = [A_1; A_2; A_3; ... ; A_n]

This was created from vertcat. Now I need to take the i-th and j-th, say the 3rd and 5th, nonzero element of every other sparse matrix from A_2 to A_{N-1} (I know the notation for this actually isn't allowed, but just for demonstrative purposes). I'd like to accomplish this without using for-loops if possible.

Upvotes: 2

Views: 2820

Answers (1)

Florian Brucker
Florian Brucker

Reputation: 10375

You can find the non-zero elements using find:

>> A = speye(3)

A =

   (1,1)        1
   (2,2)        1
   (3,3)        1

>> I = find(A ~= 0)

I =

     1
     5
     9

If you need the indices in row/column format, use ind2sub:

>> [X, Y] = ind2sub(size(A), I)

X =

     1
     2
     3

Y =

     1
     2
     3

Upvotes: 4

Related Questions