Remove array elements if a certain condition is met with a for loop
15 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
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;
0 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Calculus 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!