Delete rows from a matrix using for loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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?
0 comentarios
Respuesta aceptada
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);
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);
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!