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

16 vues (au cours des 30 derniers jours)
Austin Bollinger
Austin Bollinger le 6 Juin 2022
Réponse apportée : Voss le 6 Juin 2022
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

Réponse acceptée

Voss
Voss le 6 Juin 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;

Plus de réponses (1)

Matt J
Matt J le 6 Juin 2022
Value( all(abs(JDF)<=2.5,2) )=[];

Catégories

En savoir plus sur Loops and Conditional Statements 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!

Translated by