Can I nest an if statement in a for loop?

3 views (last 30 days)
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

Adam
Adam on 11 Dec 2014
Edited: Adam on 11 Dec 2014
Yes, you can put an if statement inside a for loop.
Your syntax for the for loop is invalid though, not the if statement even though the code analyser may erroneously accuse the if statement.
for k = [x3,...xN]
is not valid syntax.
If you have n-2 different variables named x3,...xN then you should change your code to just have a single array x with the all the values contained in the array and index into it.
  2 Comments
Sean de Wolski
Sean de Wolski on 11 Dec 2014
Adam, that actually is valid if expanded (i.e. no ellipsis)
for ii = [1 3 9 4 pi]
disp(ii)
end
Adam
Adam on 11 Dec 2014
That's true, I assumed the ellipsis was a fundamental part of the code.

Sign in to comment.

More Answers (1)

vivek cheruvu
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
Steven Lord on 9 Aug 2016
From the documentation for the if keyword:
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.
You probably want to use logical indexing as shown on this documentation page.
vivek cheruvu
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.

Sign in to comment.

Categories

Find more on Multidimensional Arrays 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!