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

조회 수: 1 (최근 30일)
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년 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by