필터 지우기
필터 지우기

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

조회 수: 5 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by