Delete rows from a matrix using for loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
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);
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!