How do I store user input values from a for loop?

2 ビュー (過去 30 日間)
Karl
Karl 2014 年 10 月 14 日
コメント済み: Mikhail 2014 年 10 月 14 日
Below is my code, The user tells the program how many resistors are they want and then they tell what value they want for each resistor. My question is, how do I store the multiple values in a vector and add them up?
x is the number of resistors the user wants.
%code
for R=1:x
R=input('What are the values of the resistors: ');
end

回答 (2 件)

Mikhail
Mikhail 2014 年 10 月 14 日
Create a vector to store your data,say,a:
a=zeros(x,1)
in for loop save values on each step:
for R=1:x
a®=input('What are the values of the resistors: ');
end
to sum up all values in your vector use sum: y=sum(a)
  1 件のコメント
Mikhail
Mikhail 2014 年 10 月 14 日
sorry, that is
a(R )=input('What are the values of the resistors: ');

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


Star Strider
Star Strider 2014 年 10 月 14 日
I would have the user enter the entire number of desired values at once:
R=input('What are the values of the resistors: ','s');
Rs = str2num(R);
In the Command Window then, the user would enter the resistor values all at once:
What are the values of the resistors: 1000 3300 47000 1500
so that:
Rs =
1.0000e+003 3.3000e+003 47.0000e+003 1.5000e+003
That seems to me to be the easiest way, and it avoids the loop. The ‘Rs’ variable in this instance is a 1x4 double.

カテゴリ

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