Can I nest an if statement in a for loop?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Adam
le 11 Déc 2014
Modifié(e) : Adam
le 11 Déc 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 commentaires
Sean de Wolski
le 11 Déc 2014
Adam, that actually is valid if expanded (i.e. no ellipsis)
for ii = [1 3 9 4 pi]
disp(ii)
end
Plus de réponses (1)
vivek cheruvu
le 9 Août 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 commentaires
Steven Lord
le 9 Août 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
le 9 Août 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.
Voir également
Catégories
En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!