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

1 回表示 (過去 30 日間)
Sandra
Sandra 2011 年 2 月 8 日
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!

回答 (2 件)

Oleg Komarov
Oleg Komarov 2011 年 2 月 8 日
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 件のコメント
Oleg Komarov
Oleg Komarov 2011 年 2 月 9 日
Ismembc is a mex helper in ismember. Much faster in case your input is sorted.
j dr
j dr 2011 年 4 月 11 日
I see !

サインインしてコメントする。


j dr
j dr 2011 年 2 月 8 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by