Combining if and for loop
4 views (last 30 days)
Show older comments
Hi all!
I am trying to combine an if and for loop in the same line. From what I have seen, it is not possible to do it directly. I have tried different ways but don't seem to find the correct way to write my code...
To explain: I am using my code to test out wether parts of my data meet certain threshold values. If this value is met, then it should do the function, otherwise test the next threshold and so on. If none of those thresholds are met, it should do the 'else' part where I have defined some other function: 'FunctionElse'.
My problem lies with the 'elseif Acc(i,3) > Threshold3'. What I want to do is for the code to check 2 things. First, I want it to check if Acc(i,3) > Threshold3, which does work. At the same time, I want the code to check if the 20 values before and after are equal to 0. If they are all equal to 0, I want it to do my self defined function 'Up'. However if it is not true, I want the function to go to the last 'else' where I can do my final function: 'FunctionElse'. However this is not working. See code below
for i = 1+2*l:N-2*l
if Gyr_1(i,3)>Threshold1
[Acc_2, Gyr_2] = Turn(Acc_1, Gyr_1, k, l); % This is a function I defined
elseif Gyr_1(i,1)>Threshold2 || Gyr_1(i,2)>Threshold2
[Acc_2, Gyr_2] = Grad(Acc_1, Gyr_1, k, l); % This is a function I defined
elseif Acc_1(i,3)>Threshold3
for m = -20:20
if Acc_1(i+m,3) == 0
Val_Accz = Val_Accz + 0;
else
Val_Accz = Val_Accz + 1;
end
end
if Val_Accz == 0
[Acc_2, Gyr_2] = Up(Acc_1, k, l);
else
return % If it is not true, I want the function to go to the next else
end
else
[Acc_2, Gyr_2] = FunctionElse(Acc_1, Gyr_1, k, l) % Do some other type of function / Should also come here if Val_Accz ~= 0
end
end
Can any of you help me with this little problem?
Thank you in advance for your help!
Hope I explained my problem well enough
Samuel :)
0 Comments
Accepted Answer
Jan
on 4 Feb 2021
Edited: Jan
on 4 Feb 2021
I assume you mean:
elseif Acc_1(i, 3) > Threshold3 && ~any(Acc_1(i-20:i+20, 3)) % [TYPO FIXED]
[Acc_2, Gyr_2] = Up(Acc_1, k, l);
else
But is it really wanted to test Acc_1(i,3) > Treshold3 and Any(i,3)==0 ?
So maybe you want to exclude Acc_1(i,3) from the check for zeros:
elseif Acc_1(i, 3) > Threshold3 && ... % [TYPO FIXED]
~any(Acc_1(i-20:i-1, 3)) && ~any(Acc_1(i+1:i+20, 3))
[Acc_2, Gyr_2] = Up(Acc_1, k, l);
else
2 Comments
Jan
on 4 Feb 2021
The error comes from a typo in my code. Replace:
all(Acc_1(i-20:i+20), 3)
% by
all(Acc_1(i-20:i+20, 3))
The first one calculates all() over the 3rd dimension, but you want the 3rd column of Acc_1.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!