Delete rows from a matrix using for loop

1 visualización (últimos 30 días)
Juan Pérez Álvarez
Juan Pérez Álvarez el 20 de Feb. de 2022
Respondida: Voss el 20 de Feb. de 2022
Hello, I need delete rows from a matrix based on a logical condition of an array using for loops:
I need delete rows from this matrix:
Matrix = [ 1,1 ; 1,2 ; 1,3 ; 2,1 ; 2,2 ; 2,3 ];
Based on this array:
Vec = [0,-0.5,-1,0.5,0,-0.5];
if any element of Vec is < 0, I need delete the index rows of this condition from the Matrix.
And I need a new matrix
MatrixAux = [1,1 ; 1,3 ; 2,2];
I try this code:
LM = length(Matrix);
MatrixAux [];
for i =1: LM
if Vec(i) < 0
MatrixAux(i,:) = Matrix(i,:);
end
end
Any idea?

Respuesta aceptada

Voss
Voss el 20 de Feb. de 2022
The MatrixAux in your example doesn't seem to correspond to the process you decribe. Maybe I'm misunderstanding, but it seems like you can do this (no for loops required):
Matrix = [ 1,1 ; 1,2 ; 1,3 ; 2,1 ; 2,2 ; 2,3 ];
Vec = [0,-0.5,-1,0.5,0,-0.5];
idx_to_delete = Vec < 0;
Matrix(idx_to_delete,:) = [];
disp(Matrix);
1 1 2 1 2 2
or more simply:
Matrix = [ 1,1 ; 1,2 ; 1,3 ; 2,1 ; 2,2 ; 2,3 ];
Vec = [0,-0.5,-1,0.5,0,-0.5];
Matrix(Vec < 0,:) = [];
disp(Matrix);
1 1 2 1 2 2

Más respuestas (0)

Categorías

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

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by