reset the counter in for loop
37 ビュー (過去 30 日間)
古いコメントを表示
I want to check the values in an array but when i reset the counter it ignores the new definition and continues looping. Why that happens and if there is a better way to do it please help. Thanks in advance
v=input('Enter an array of positive numbers:');
for i=1:length(v)
while v(i) <= 0
v=input('Error:Enter an array of positive numbers:');
i=1;
end
end
0 件のコメント
回答 (2 件)
JESUS DAVID ARIZA ROYETH
2019 年 11 月 16 日
編集済み: JESUS DAVID ARIZA ROYETH
2019 年 11 月 16 日
because the for loop once defined ignores some change in its variable and tries to execute normally, but with this you can solve your problem:
v=input('Enter an array of positive numbers:');
while sum(v<=0)>0
v=input('Error:Enter an array of positive numbers:');
end
7 件のコメント
Walter Roberson
2019 年 11 月 17 日
I have to wonder if you had accidentally created a variable named sum
Adam Danz
2019 年 11 月 16 日
編集済み: Adam Danz
2022 年 11 月 3 日
You cannot alter the for-loop counter. It is possible to temporarily override the value of the loop variable but it will reset to the next iteration value when the loop continues to the next iteration, though this is not advisable.
Here's an alternative that continually asks the user for a vector of positive numbers until those condtions are satisfied and then it moves on to your for-loop.
Instead of using input() it uses inputdlg() which is a bit cleaner IMO but that line can be replaced with input() if that is preferred. Additionally, it converts the char input to double (numeric).
v = NaN;
while any(isnan(v)) || any(v<0)
response = inputdlg('Enter a vector of positive numbers');
v = str2double(strsplit((response{:})));
end
for i=1:length(v)
% Do stuff
end
Example with input() instead.
v = [];
while isempty(v) || ~isnumeric(v) || any(v < 0)
v = input('Enter a vector of positive numbers: ');
end
for i=1:length(v)
% Do stuff
end
5 件のコメント
Steven Lord
2022 年 11 月 1 日
You can change the for loop counter. But I'm pretty sure it's always been the case that the change will only be present for the rest of the current iteration and that when the for loop enters its next iteration the loop variable will be assigned the next value from the for loop expression, overwriting the changed value. I just launched a very old release of MATLAB (release R11) and confirmed that this behavior occurs in that release. So that makes this behavior at least 22 years old. [I forget exactly when release R11 came out.]
for k = 1:10
if k == 5
k = 1;
end
disp(k)
end
1
2
3
4
1
6
7
8
9
10
The loop variable did change in the iteration when the expression gave it the value 5, but that did not "restart the loop" or anything like that. The next iteration it took the next value from the expression 1:10.
参考
カテゴリ
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!