MATLAB Answers

reset the counter in for loop

34 views (last 30 days)
Khalid Mamdouh
Khalid Mamdouh on 16 Nov 2019
Commented: Walter Roberson on 17 Nov 2019
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 Comments

Sign in to comment.

Answers (2)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 16 Nov 2019
Edited: JESUS DAVID ARIZA ROYETH on 16 Nov 2019
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 Comments

Show 4 older comments
Adam Danz
Adam Danz on 16 Nov 2019
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 on 16 Nov 2019
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 on 17 Nov 2019
I have to wonder if you had accidentally created a variable named sum

Sign in to comment.


Adam Danz
Adam Danz on 16 Nov 2019
Edited: Adam Danz on 16 Nov 2019
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 Comments

Walter Roberson
Walter Roberson on 16 Nov 2019
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 on 16 Nov 2019
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.

Sign in to comment.


Translated by