MATLAB Answers

0

reset the counter in for loop

Asked by Khalid Mamdouh on 16 Nov 2019 at 20:30
Latest activity Commented on by Walter Roberson
on 17 Nov 2019 at 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 Comments

Sign in to comment.

2 Answers

Answer by JESUS DAVID ARIZA ROYETH on 16 Nov 2019 at 20:52
Edited by JESUS DAVID ARIZA ROYETH on 16 Nov 2019 at 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 Comments

Adam Danz
on 16 Nov 2019 at 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 on 16 Nov 2019 at 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
on 17 Nov 2019 at 3:27
I have to wonder if you had accidentally created a variable named sum

Sign in to comment.


Answer by Adam Danz
on 16 Nov 2019 at 21:01
Edited by Adam Danz
on 16 Nov 2019 at 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 Comments

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

Sign in to comment.