How to find the indices of non-zero elements in a matrix

121 views (last 30 days)
I have an Na-by-Nt matrix which is sparse, i.e.: most elements are zeros. I want to find the indices of the non-zeros elements in the form of (i,j) where i is the row and j is the column.
I have then these two Na-by-1 vector a and Nt-by-1 vector tau. i corresponds to the ith element in a and j the jth element in tau, and I want to find them as well.
How can I do the above in an efficient way without the need for for loops?

Answers (1)

Cedric Wannaz
Cedric Wannaz on 27 Jun 2014
Edited: Cedric Wannaz on 27 Jun 2014
If it is for storing only non-zero elements, MATLAB supports SPARSE matrices. If you need to get row/column indices of non-zero elements of A:
[rId, cId] = find( A ) ;
and if you need values as well:
[rId, cId, val] = find( A ) ;
If you just need values, you can get them simply with
vals = A(A ~= 0) ;
S. David
S. David on 30 Jun 2014
Edited: S. David on 30 Jun 2014
It is difficult to give a non real example. However, I think it is not necessary to understand the code/algorithm. At the end, the code will give A, v, and the sparse solution xVec. That is all is needed I guess.

Sign in to comment.


Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by