Delete rows from a matrix using for loop

1 vue (au cours des 30 derniers jours)
Juan Pérez Álvarez
Juan Pérez Álvarez le 20 Fév 2022
Réponse apportée : Voss le 20 Fév 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?

Réponse acceptée

Voss
Voss le 20 Fév 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

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by