How to quickly find the first non-zero element without iterations in all columns in a sparse matrix?
84 views (last 30 days)
Show older comments
Commented: Matt J on 19 Mar 2020
I have a big sparse matrix A. I want to find out the first non-zero element in all columns from the top. Here is my code:
reorderCol = ;
for jCol = 1 : length(A(1,:))
eee = find(A(:,jCol),1,'first');
reorderCol = [reorderCol eee];
For example, I have matrix A = [0 0 0;0 5 0;0 0 1;0 0 0;-1 0 -4]. My code gives the following result:
reorderCol = [5 2 3];
I am wondering if it is possible to obtain reorderCol without iterations. Thanks a lot.
Yes, it's a simple modification. See here,
More Answers (3)
KSSV on 18 Mar 2020
[val,id] = min(abs(A)) ;
Use the minimum function.
Les Beckham on 18 Mar 2020
Edited: Les Beckham on 18 Mar 2020
Try this. In my test with a 1000x1000 random sparse 0 or 1 matrix (A = sparse(randi([0 1], 1000, 1000));) it is about 4 times faster.
i = find(A(:) ~= 0, 1, 'first');
ij = ind2sub(size(A), i);
For a 5000x5000 A it is actually slower, however (about 83% as fast).
Note that I am using Octave as I don't currently have access to Matlab.
Iteration is not always necessary, or desirable, to avoid. In fact, many of the Matlab 'tricks' are just iteration in disguise.
I hope this helps.
Perhaps your results will be different using Matlab vs. Octave. Let me know.
See this FEX submission,
Find more on Matrix Computations 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!