How to scan a matrix row by row and execute certain commands if conditions are met.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Akzeptierte Antwort
Voss
am 21 Mär. 2022
Bearbeitet: Voss
am 21 Mär. 2022
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
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!