How to delete nonzero values at the end of a matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
Assume I have the following array:
M = [1 1 1; 0 2 2; 3 3 0; 4 4 0; 0 5 0]
How do I set all elements from the end of each row to the first nonzero value to NaN?
The result should look like this:
M = [1 1 1; 0 2 2; 3 3 NaN; 4 4 NaN; NaN 5 NaN]
It is important that only the zero values at the end are set equal to NaN and not all elements that are equal to zero.
Thank you!
댓글 수: 0
채택된 답변
Chunru
2021년 8월 13일
M = [1 1 1; 0 2 2; 3 3 0; 4 4 0; 0 5 0]
for i=1:size(M, 2)
idx = find(M(:, i), 1, 'last');
M(idx+1:end, i) = nan;
end
M
%M = [1 1 1; 0 2 2; 3 3 NaN; 4 4 NaN; NaN 5 NaN]
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!