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

5 次查看(过去 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