Remove array elements if a certain condition is met with a for loop

26 visualizaciones (últimos 30 días)
I am trying to use a for loop to find the values between -2.5 to 2.5 in the first two columns of a matrix and remove all the rows of the matrix when the conditon is met with the values between -2.5 to 2.5. I am just trying to ignore these data points.Is there a way to do this with negative numbers?
JDF = [CorrCKASRoll1,CorrCKASPitch1,CorrJoystickRoll1,CorrJoystickPitch1];
CKASR = JDF(:,1);
CKASP = JDF(:,2);
x = size(CKASR);
Value = zeros(x);
for i = 1:length(CKASR)
if ((CKASR(i)>=-2.5)&&(CKASR(i)<=2.5))&&((CKASP(i)>=-2.5)&&(CKASP(i)<=2.5))
Value = [];
end
Value;
end

Respuesta aceptada

Voss
Voss el 6 de Jun. de 2022
Here's one way, using a for loop:
JDF = [CorrCKASRoll1,CorrCKASPitch1,CorrJoystickRoll1,CorrJoystickPitch1];
CKASR = JDF(:,1);
CKASP = JDF(:,2);
x = numel(CKASR);
to_remove = false(x,1);
for i = 1:x
if ((CKASR(i)>=-2.5)&&(CKASR(i)<=2.5))&&((CKASP(i)>=-2.5)&&(CKASP(i)<=2.5))
to_remove(i) = true;
end
end
% remove rows from CKASR and CKASP:
CKASR(to_remove,:) = [];
CKASP(to_remove,:) = [];
% and/or, remove rows from JDF itself:
JDF(to_remove,:) = [];
However, it's more efficient to use logical indexing instead of a for loop (note: you must use & instead of && for vectors):
JDF = [CorrCKASRoll1,CorrCKASPitch1,CorrJoystickRoll1,CorrJoystickPitch1];
CKASR = JDF(:,1);
CKASP = JDF(:,2);
to_remove = (CKASR>=-2.5) & (CKASR<=2.5) & (CKASP>=-2.5) & (CKASP<=2.5);
% remove rows from CKASR and CKASP:
CKASR(to_remove,:) = [];
CKASP(to_remove,:) = [];
% and/or, remove rows from JDF itself:
JDF(to_remove,:) = [];
Also, note that ((CKASR>=-2.5)&&(CKASR<=2.5)) is equivalent to abs(CKASR)<=2.5 (if CKASR is real) - and similarly for CKASP - so you can say:
to_remove = abs(CKASR)<=2.5 & abs(CKASP)<=2.5;

Más respuestas (1)

Matt J
Matt J el 6 de Jun. de 2022
Value( all(abs(JDF)<=2.5,2) )=[];

Categorías

Más información sobre Loops and Conditional Statements 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!

Translated by