How to scan a matrix row by row and execute certain commands if conditions are met.

조회 수: 1 (최근 30일)
I have a Matrix ....
A =
12 0 0
0 0 0
0 13 0
0 0 0
0 0 0
0 0 11
I want to ...
Scan the first row of the matrix.
--> If any of the values in the row are > 0, then assign that value to 1, but keep the others as 0, and move to the next row.
--> However, if all of the values in the row equal 0, then look to see which of them immediately follow a value that is > 0. Replace that 0 with a 1. Keep the others as 0. Move to next row of the matrix.
Carry on with the steps above , until you reach last row of the matrix.
Therefore, Matrix A should look like this at the end:
A =
1 0 0
1 0 0
0 1 0
0 1 0
0 1 0
0 0 1
Thank you!

채택된 답변

Voss
Voss 2022년 3월 21일
편집: Voss 2022년 3월 21일
A = [12 0 0
0 0 0
0 13 0
0 0 0
0 0 0
0 0 11];
% scan each row of A
for ii = 1:size(A,1)
% find the index of non-zero elements in the row
idx = find(A(ii,:));
% if there are none (the row is all zeros)
if isempty(idx)
% if it's not the first row
if ii > 1
% find the index of non-zero elements in the previous row
idx = find(A(ii-1,:));
% set the elements at those indices in this row to 1
A(ii,idx) = 1;
end
else % if there are some non-zero elements in the row, set them to 1
A(ii,idx) = 1;
end
end
A
A = 6×3
1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 1

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by