Stay in the loop without changing counter until condition met
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Stephen23
2016-8-6
编辑:Stephen23
2016-8-6
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!