How to quickly find the first non-zero element without iterations in all columns in a sparse matrix?

조회 수: 65 (최근 30일)
Hi, All,
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];
end
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.
Benson

채택된 답변

Matt J
Matt J 2020년 3월 19일
[~,result]=max(logical(A),[],1);
  댓글 수: 3
Benson Gou
Benson Gou 2020년 3월 19일
Hi, Matt,
Do you think I can use your code to do the same thing for the rows in a sparse matrix? I want to find the index of the LAST non-zero element in each row in A.
For example, I have matrix A = [2 0 0;0 5 0;0 0 1;0 3 0;-1 0 -4]. My code gives the following result:
reorderRow = [1 2 3 2 3];
Thanks a lot.
Benson

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

KSSV
KSSV 2020년 3월 18일
[val,id] = min(abs(A)) ;
Use the minimum function.
  댓글 수: 1
Benson Gou
Benson Gou 2020년 3월 18일
Hi, KSSV, thanks for your reply. I am sorry for the unclarity of my statement. I am looking for the position of the first non-zero element in each column, not the value of the first non-zero element. Thanks!
Benson

댓글을 달려면 로그인하십시오.


Les Beckham
Les Beckham 2020년 3월 18일
편집: Les Beckham 2020년 3월 18일
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.
  댓글 수: 1
Benson Gou
Benson Gou 2020년 3월 19일
Hi, Les,
I tried your code. I found it only gives me one integer which is the first non-zero lement in the first column in A. How can I apply for all the columns in A? Thanks.
Benson

댓글을 달려면 로그인하십시오.


Matt J
Matt J 2020년 3월 19일

카테고리

Help CenterFile Exchange에서 Discrete Fourier and Cosine Transforms에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by