Can I nest an if statement in a for loop?
Show older comments
Question as above, supposedly the following code uses an illegal use of a reserved keyword (if), why is this?
for k = [x3,...,xN]
k == 0.5*(x1+x2);
if sign(f(k)) == sign(f(x1))
k = x1;
else
k=x2;
end
end
Accepted Answer
More Answers (1)
vivek cheruvu
on 9 Aug 2016
Hi,
I am trying to nest an IF statement inside a FOR loop, but when I try to run the code, the program skips the code that follows the IF statement and throws me an error. I have provided the piece of code where, I kind of get confused. Any sort of help will be appreciated.
Here is my code:
size = length(voltage)
for i = 1:size
SOC1 = energy/1640; % Energy is imported from a text file (4778x1)%
if (0 < SOC1 < 0.05)
Vcb = 12*SOC1+2.5;
elseif (0.05< SOC1 < 0.99)
Vcb = 0.66*SOC1+3.2;
else
errordlg('SOC out of bound');
{ this is followed by complex equations }
end
end
PS: I have tried using (0 < SOC1)&&(SOC1 < 0.05) this as well, nothing is working out.
2 Comments
Steven Lord
on 9 Aug 2016
An expression is true when its result is nonempty
and contains only nonzero elements
If SOC1 is a vector, "if (0 < SOC1) & (SOC1 < 0.05)" will only execute the expression in the if section of the if / elseif / else / end statement if ALL the elements of SOC1 are greater than 0 and less than 0.05. If even one element fails either of those tests, the if condition is not satisfied and MATLAB will move to the elseif section.
vivek cheruvu
on 9 Aug 2016
Hello Steven,
Thanks for your answer. But still, when I change the SOC1 value to 0.1, it skips the loop. SOC1 is not a vector, it will create a vector by iterating through the loop.
Categories
Find more on System on Chip (SoC) 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!