Can I nest an if statement in a for loop?

조회 수: 4 (최근 30일)
Michael
Michael 2014년 12월 11일
댓글: vivek cheruvu 2016년 8월 9일
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