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

1 visualizzazione (ultimi 30 giorni)
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!

Risposte (2)

Oleg Komarov
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 Commenti
Oleg Komarov
Oleg Komarov il 9 Feb 2011
Ismembc is a mex helper in ismember. Much faster in case your input is sorted.

Accedi per commentare.


j dr
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

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