MATLAB Answers

reset the counter in for loop

53 ビュー (過去 30 日間)
Khalid Mamdouh
Khalid Mamdouh 2019 年 11 月 16 日
コメント済み: Walter Roberson 2019 年 11 月 17 日
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
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 件のコメント

表示 4 件の古いコメント
Adam Danz
Adam Danz 2019 年 11 月 16 日
Note that if the user presses enter without entering anything in response to input(), it will return an empty [ ] and since sum([]<=0) == 0, the user will not be prompted again. That may be desired or it may not be - just something to keep in mind.
Khalid Mamdouh
Khalid Mamdouh 2019 年 11 月 16 日
Is sum(v<=0) works on 2007 version because I tried it and it prompts an error 'Index exceeds matrix dimensions'
Walter Roberson
Walter Roberson 2019 年 11 月 17 日
I have to wonder if you had accidentally created a variable named sum

サインインしてコメントする。


Adam Danz
Adam Danz 2019 年 11 月 16 日
編集済み: Adam Danz 2019 年 11 月 16 日
You cannot alter the for-loop counter. 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

  2 件のコメント

Walter Roberson
Walter Roberson 2019 年 11 月 16 日
You can alter the for loop counter. However, the next time the for loop would execute, it will change the counter back.
Adam Danz
Adam Danz 2019 年 11 月 16 日
You can override the counter variable within the loop but I was referring to the counter controlling the number of iterations. Thanks for the clarification.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by