error checking wont replace old input

1 view (last 30 days)
This is my code and I want to error check it for the person to input a vector of grades that are from 0 to ten. Every time I run it once with the correct grades [1 2 3], it works. However, if I run it with a wrong vector [-1 2 3] then a correct one [1 2 3], it keeps telling me to enter another vector. I checked my workspace and it appears that the first vecgrade isnt being replaced by the second one.
clear all; clc
vecgrade=input('Enter a vector of quiz grades: \n');
vecchecker=vecgrade>=0 & vecgrade<=10;
while all(vecchecker)==0
vecgrade=input('Please enter another vector of quiz grades: \n');
vecchecker=vecgrade<0 & vecgrade>10;
end
vecgrade

Accepted Answer

Geoff Hayes
Geoff Hayes on 16 Nov 2014
David - your re-initialization of vecchecker in the while loop uses a different condition than the one outside of the while loop. Note that if
vecgrade = [1 2 3];
vecchecker=vecgrade<0 & vecgrade>10;
then
vecchecker =
0 0 0
Which makes sense because the condition is saying if the grade is less than zero and greater than ten - which is impossible, so the vector is all zeros (false).
Change your re-initialization of this local variable to be the same as that outside of the loop
vecchecker=vecgrade>=0 & vecgrade<=10;
and your code should work fine.
  1 Comment
David Phung
David Phung on 16 Nov 2014
Oh my! Thank you so much. I cant believe I didnt catch that error :(

Sign in to comment.

More Answers (0)

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!