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

2 visualizzazioni (ultimi 30 giorni)
Sandra il 8 Feb 2011
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!
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Risposte (2)

Oleg Komarov il 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 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
j dr il 11 Apr 2011
I see !

Accedi per commentare.

j dr il 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
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by