Can I nest an if statement in a for loop?

3 次查看(过去 30 天)
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

采纳的回答

Adam
Adam 2014-12-11
编辑:Adam 2014-12-11
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 个评论
Sean de Wolski
Sean de Wolski 2014-12-11
Adam, that actually is valid if expanded (i.e. no ellipsis)
for ii = [1 3 9 4 pi]
disp(ii)
end
Adam
Adam 2014-12-11
That's true, I assumed the ellipsis was a fundamental part of the code.

请先登录,再进行评论。

更多回答(1 个)

vivek cheruvu
vivek cheruvu 2016-8-9
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 个评论
Steven Lord
Steven Lord 2016-8-9
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 2016-8-9
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by