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

3 ビュー (過去 30 日間)
Laura Steel
Laura Steel 2022 年 3 月 21 日
コメント済み: Voss 2022 年 3 月 21 日
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
  2 件のコメント
Laura Steel
Laura Steel 2022 年 3 月 21 日
Thank you very much! This works perfectly :)
Voss
Voss 2022 年 3 月 21 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by