Want to create a loop that gets 12 arbitrary numbers between 1-20 from the keyboard

1 Ansicht (letzte 30 Tage)
I want to create a function or just an m-file that reads 12 arbitrary numbers, from the keyboard to a vector one at a time. The numbers should be in the range 0-20.
This is what I did so far but it doesn't work.
c=zeros(1,12);
for i=1:12, c=input('Write 12 numers between 0-20: ','s'); %I don't necesarely want it to ask everytime but I dont know how to make it ask one time. c(i+1)=c;
%if x>=20 (to get an error message if you type in the wrong number) %p='Error'; %p %end
end
Hope somebody can help!

Antworten (2)

Oleg Komarov
Oleg Komarov am 8 Feb. 2011
An example of code, you can make more robust introducing more checks:
% Preallocate
c = zeros(12,1);
% Set counter
ii = 1;
while ii <= 12
% Get value
c(ii) = input('Write 12 numers between 0-20: ');
% Check if in [0-20]
if ismembc(c(ii),0:20)
ii = ii+1;
else
fprintf('\nWARNING: Only values between 0-20!\n')
end
end
Oleg
  3 Kommentare
Oleg Komarov
Oleg Komarov am 9 Feb. 2011
Ismembc is a mex helper in ismember. Much faster in case your input is sorted.

Melden Sie sich an, um zu kommentieren.


j dr
j dr am 8 Feb. 2011
you're using "c" as your input vector but then you're not filling it, you're redefining it
c=zeros(1,12);
for i=1:12,
c(i)=str2num(input('Write 12 numers between 0-20: ','s'));
if c(i)>20 || c(i)<0
error('You have to specify a number between [0-20], now start over')
end
end
disp(c)
This should work

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by