change the iteration in for loop
6 次查看(过去 30 天)
显示 更早的评论
I have For Loop that calculate c. Sometimes c become nan or big number.
When I get big amount or Nan for c, I want to repeat that iteration again.
I used this code but does not repeat that iteration.
for i=1:10
% calculate c
if isnan(c(i))==1 | c(i)>0.009
i=i-1 % again repeat the iteration
end
end
2 个评论
KALYAN ACHARJYA
2019-7-15
Naime Comments:
I think '|' and '||' does not have a difference.
when it goes to if part, c become zero on that iteration.
it means that does not repeat that iteration.
for example in i=2, c(2)=nan. when I use this code i=1, but in for loop it starts from 3.
Big number in my case more than 0.009
KALYAN ACHARJYA
2019-7-15
Naime Comments:
m=m-1; % matlab gives me this detail
it appears that the index value of the indicated for loop changes inside the loop body. Often, this happens when loops nest and an inner loop reuses the name of an outer loop index. Because MATLAB resets the loop index to the next value when it returns to the top of the outer loop, it ignores any changes that took place within a nested loop. If the code does not to refer to the outer loop index value after the inner loop changes it, no problem results. However if you attempt to use the outer loop index value after the inner loop completes, it is likely to result in a bug.
回答(2 个)
Andy
2019-7-15
I don't think the For loop is what you need.
i =1;
while i<11
% calculate c
if isnan(c(i))==0 & c(i)<=0.009
i=i+1;
end
end
2 个评论
Andy
2019-7-16
I made up this code, adding the else just to change the value and it works fine.
i=1;
c=[ .001 12 .003 .004 nan .006 .007 .008 nan .005];
while i<11
%calculate c
if isnan(c(i))==0 & c(i)<=.009
i=i+1;
else
c(i)
c(i)=0;
end
end
c
KALYAN ACHARJYA
2019-7-15
编辑:KALYAN ACHARJYA
2019-7-15
# Experts need your suggestions here
for i=1:10
c(i)=...% do
while isnan(c(i)) || c(i)>0.009
c(i)=..
end
end
I know multiple loop is messed here, just try to get way out. Hope I undestand the question.
One Note: Without changing i, is there any possibilty to change the C(i) in next or next iterartions within while loop, so that once it fail, it exit from while loop?
The code runs within the while loop, without changing i ultill C(i) satisfy any one conditions-
- C(i) is NaN
- C(i)>0.009
2 个评论
KALYAN ACHARJYA
2019-7-15
编辑:KALYAN ACHARJYA
2019-7-15
when i=4, nan happens so I want to repeat i=4 to get some result
When NaN appears, it enter to within while loop, while loop doesnot change the i value. When c(i)=Nan at i=4, it keep running withing while loop, that why I asking, is there any possibility to change C(i) result without changing i, so that it exit from while loop?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!