Delete rows from a matrix using for loop

1 view (last 30 days)
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?

Accepted Answer

Voss
Voss on 20 Feb 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

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!