フィルターのクリア

Storing user input as a vector

10 ビュー (過去 30 日間)
Justin
Justin 2011 年 2 月 21 日
回答済み: Rupashree Nakkeeran 2018 年 8 月 14 日
I am asking a user for a positive number using a "while" loop. I want to store the numbers that the user gives me in a single row array and then perform several operations on the array of numbers. For example: input a number: 3 input a number: 4 input a number: 2 input a number: 2
I want an array of [3 4 2 2], but all I can get is [0 2 3 4]. I'm using
x = input ('input a number') number(x) = x
inside a while loop. Please help

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 2 月 21 日
x = zeros(1,100); %assuming no more than 100 values
cnt = 0;
while 1
cnt = cnt+1;
x(cnt) = input('d....');
if some_condition
break;
end
end
x = x(1:cnt);
  1 件のコメント
Student
Student 2018 年 3 月 29 日
Instead of stopping at 100, is there a way I can make the number of values stop when the user types "Stop" or "Done" or something similar to that?

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

その他の回答 (2 件)

Sam G.
Sam G. 2011 年 2 月 21 日
You need a separate variable to indicate the array index you want to store the number in. In your example, the user enters '2' twice. Since you are using the input to specify the index, the second '2' overwrites the first '2'. I'd use end and do something like this.
x = [];
while 1
x(end+1) = input('Input a number: ');
if some_condition; break; end
end

Rupashree Nakkeeran
Rupashree Nakkeeran 2018 年 8 月 14 日
You can also do it the following way,
limit=input('Enter limit=');
n=1;
while n<=limit
x(1,n)=input(' ');
n=n+1;
end;
disp(x)

カテゴリ

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