MATLAB Answers

Finding last non-zero rows for individual columns of a matrix without loops

조회 수: 4(최근 30일)
J AI 20 Jun 2020
댓글: J AI 20 Jun 2020
I have the following code:
A =[1 2 3;
1 0 1;
0 5 1;
1 0 2;
2 3 2];
[row,~] = find(A(1:4,[1,2]),1,'last');
What I was hoping to achieve through the above code is to find the last non-zero rows for individual columns. So my expected answer was
row = [4 3] % since for the first column, the first non-zero element is on 4th row and similarly on 3rd row for the second column
However, with the above code, the answer I am getting is
row = 3
I have done it with a for loop, but with the size of data I have, it is computationally expensive to do loops. I was hoping to get it done without loops.
Thank you in advance for your kind contribution.

  댓글 수: 0

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

채택된 답변

per isakson
per isakson 20 Jun 2020
Try this
[r,c] = find( A==0 );
[~,ixa] = unique( c, 'last' );
>> r(ixa)
ans =

  댓글 수: 2

J AI 20 Jun 2020
This seems to work just fine. Thanks a lot for your contribution.
J AI 20 Jun 2020
I apologize for a slight mistake in my question, because the answer I was looking for was [4,3] instead of [3,4] (I have modified my question) since I am looking for non-zero elements, and not zero elements. However, your approach is still correct with a slight modification like this one:
[r,c] = find( A(1:4,1:2)~=0 )
[~,ixa] = unique( c, 'last' )
Thank you once again!

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

추가 답변(0개)




Translated by