How to find the last 1 in every row
    조회 수: 4 (최근 30일)
  
       이전 댓글 표시
    
Say I have a matrix
A = [0 1 1 1 0;
     1 1 1 0 0;
     0 1 1 1 0]
What's the fastest way to find the last 1 in each row? The output should be
ans = [2; 3; 2];
So far I have come up with this:
[~, I] = max(fliplr(A),[],2);
I = size(A,2) + 1  - I;
댓글 수: 0
답변 (2개)
  KALYAN ACHARJYA
      
      
 2020년 11월 26일
        
      편집: KALYAN ACHARJYA
      
      
 2020년 11월 26일
  
      A=rot90(A,90);
[~,idx]=max(A==1,[],2)
Result:
idx =
     2
     3
     2
댓글 수: 0
  Bruno Luong
      
      
 2020년 11월 26일
        
      편집: Bruno Luong
      
      
 2020년 11월 26일
  
      Depending on the density of 1s, but a for-loop (remember that?) might be the fatest
function BenchMax
A=rand(10000)>0.5;
tic
[~, I] = max(fliplr(A),[],2);
I = size(A,2) + 1  - I;
toc % Elapsed time is 0.045622 seconds.
tic
[m,n] = size(A);
I = zeros(m,1);
for r=1:m
    for c=n:-1:1
        if A(r,c)
            I(r) = c;
            break
        end
    end
end
I = n+1-I;
toc % Elapsed time is 0.000437 seconds.
end
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
			
	제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


