필터 지우기
필터 지우기

cut of zeros from a matrix based on the longest non-zero row

조회 수: 1 (최근 30일)
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2021년 11월 22일
댓글: Dave B 2021년 11월 22일
Hi all,
I want to cut all zeros from the right, based on "the longest non zero row". an example:
A=[ 1 2 0 0 0 0;3 4 5 0 0 0;5 6 0 0 0 0];
output: A=[ 1 2 0 ;3 4 5 ;5 6 0 ];
thanks in advance!
  댓글 수: 1
Yongjian Feng
Yongjian Feng 2021년 11월 22일
Try it yourself first please. We can then look at the code together.

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

채택된 답변

Dave B
Dave B 2021년 11월 22일
편집: Dave B 2021년 11월 22일
Another way to phrase this question is to say you want to remove columns from the right side of the matrix if the whole column is zeros:
A=[ 1 2 0 0 0 0;3 4 5 0 0 0;5 6 0 0 0 0];
lastnonzero=find(any(A~=0,1),1,'last') % the last column with a non-zero row
lastnonzero = 3
A(:,lastnonzero+1:end)=[]
A = 3×3
1 2 0 3 4 5 5 6 0
  댓글 수: 3
Net Fre
Net Fre 2021년 11월 22일
OK, much better than mine :)
Didn't know about any. Notice that your code will ingore non-zero negatives.
Dave B
Dave B 2021년 11월 22일
oops, I updated to be ~=0, thanks for catching that! (technically it can just be any(A), but I find that specifying the condition explicitly is more readable)
any and all are very useful! they also take a dimension arg, or the keyword 'all' which I use often.

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

추가 답변 (1개)

Net Fre
Net Fre 2021년 11월 22일
편집: Net Fre 2021년 11월 22일
Hi
You can use the cumprod function.
your code line can look like this:
% a = some matrix
idx = max(sum(cumprod(a~=0,2)),2)
output = a(:,1:idx)
I suggest you break the one line into several ones just to see what each function does.
hope this helps.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by