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

19 ビュー (過去 30 日間)
Austin Bollinger
Austin Bollinger 2022 年 6 月 6 日
回答済み: Voss 2022 年 6 月 6 日
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

採用された回答

Voss
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;

その他の回答 (1 件)

Matt J
Matt J 2022 年 6 月 6 日
Value( all(abs(JDF)<=2.5,2) )=[];

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by