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

3 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Voss
Voss el 21 de Mzo. de 2022
Editada: Voss el 21 de Mzo. de 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
A = 6×3
1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 1

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by