MATLAB Answers

0

reset the counter in for loop

Khalid Mamdouh さんによって質問されました 2019 年 11 月 16 日 20:30
最新アクティビティ Walter Roberson
さんによって コメントされました 2019 年 11 月 17 日 3:27
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 件のコメント

サインイン to comment.

2 件の回答

回答者: JESUS DAVID ARIZA ROYETH 2019 年 11 月 16 日 20:52
編集済み: JESUS DAVID ARIZA ROYETH 2019 年 11 月 16 日 20:53

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 件のコメント

Adam Danz
2019 年 11 月 16 日 21:31
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 2019 年 11 月 16 日 21:47
Is sum(v<=0) works on 2007 version because I tried it and it prompts an error 'Index exceeds matrix dimensions'
Walter Roberson
2019 年 11 月 17 日 3:27
I have to wonder if you had accidentally created a variable named sum

サインイン to comment.


Adam Danz
回答者: Adam Danz
2019 年 11 月 16 日 21:01
編集済み: Adam Danz
2019 年 11 月 16 日 21:36

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
2019 年 11 月 16 日 21:10
You can alter the for loop counter. However, the next time the for loop would execute, it will change the counter back.
Adam Danz
2019 年 11 月 16 日 21:18
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.

サインイン to comment.



Translated by