Remove array elements if a certain condition is met with a for loop
15 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2022-6-6
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 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!