Stay in the loop without changing counter until condition met
1 view (last 30 days)
Show older comments
I have a loop where, say, five numerical inputs are requested from the user. And I want the inputs to be either number 1,2 or 3. If they enter anything else, I don't want the counter to work, simple to stay in the loop until they enter five numbers, all of them either 1,2 or 3. I tried while loop with break, but it didnt work. Is there anyway to do it? Here is a basic code:
i=1;
for i=1:5
Rx=input('Type in a number:');
if Rx==1
disp('one')
elseif Rx==2
disp('two')
elseif Rx==3
disp('three')
else
disp('wrong')
end
end
0 Comments
Answers (1)
Stephen23
on 6 Aug 2016
Edited: Stephen23
on 6 Aug 2016
MATLAB is most effective when you learn to use arrays to hold your data, so this task becomes quite simple when we store those values in vector:
oky = 1:3; % must match these values
vec = NaN(1,5); % output vector
while any(~ismember(vec,oky))
idx = find(~ismember(vec,oky),1,'first');
str = input(sprintf('Please enter value %d: ',idx),'s');
num = str2double(str);
if ismember(num,oky)
vec(idx) = num;
end
end
And using:
Please enter value 1: 4
Please enter value 1: 5
Please enter value 1: 2
Please enter value 2: 1
Please enter value 3: 3
Please enter value 4: 8
Please enter value 4: 8
Please enter value 4: 2
Please enter value 5: 1
and the output values are stored conveniently in one vector:
>> vec
vec = 2 1 3 2 1
You should also put a limit on the number of iterations that the loop can perform, otherwise users will have no way to exit the loop.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!