필터 지우기
필터 지우기

How to store results of for loop in 1D array.

조회 수: 3 (최근 30일)
Anna
Anna 2013년 8월 4일
댓글: mustafa alnasser 2014년 10월 6일
So i want to to store 10,000 values resulting from a for loop in a 1D array. How do I do that?
My file reads:
goal = 1000000;
needMoreMoney = true;
age = 30;
savings = 10000;
inheritence = randi(10,1,1);
rateOfReturn = (-3 + (12 - -3)*rand);
while(savings<=goal);
savings = savings + (savings * rateOfReturn) + 10000;
age = age + 1;
end
if(inheritence==4);
savings = savings + 10000;
end
hist(retirement_age)
disp('Savings made in dollars: ');
disp(num2str(savings,'%.2f'));
disp('At age: ');
disp(age);
Where do I add the for loop and how do I store the values in an array? I am very new to this so i would appreciate you using my case above to give me the answer. Thanks!
  댓글 수: 1
Jan
Jan 2013년 8월 4일
편집: Jan 2013년 8월 4일
Are you sure that the rateOfReturn should not change inside the loop?
It is not clear to me, where the FOR loop should be inserted.

댓글을 달려면 로그인하십시오.

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 4일
편집: Azzi Abdelmalek 2013년 8월 4일
goal = 1000000;
needMoreMoney = true;
age = 30;
savings = 10000;
inheritence = randi(10,1,1);
rateOfReturn = (-3 + (12 - -3)*rand);
while(savings(end)<=goal);
savings(end+1) = savings(end) + (savings(end) * rateOfReturn) + 10000;
age(end+1) = age(end) + 1;
end
if(inheritence==4);
savings(end) = savings(end) + 10000;
end
%hist(retirement_age)
disp('Savings made in dollars: ');
disp(num2str(savings,'%.2f'));
disp('At age: ');
disp(age);
  댓글 수: 1
Jan
Jan 2013년 8월 4일
Notice that this iterative growing of an array is considered as bad programming style, see http://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm . Therefore it is recommended to avoid this strictly and apply a proper pre-allocation.

댓글을 달려면 로그인하십시오.


Jan
Jan 2013년 8월 4일
The standard method for storing values in a vector is:
n = 10000;
data = zeros(1, n); % Pre-allocation!!!
for k = 1:n
data(k) = rand; % Your calculations here
end
Or when the loop counter is not sufficient as index:
data = zeros(1, n); % Pre-allocation!!!
index = 0;
for k = 10:n+9
index = index + 1;
data(index) = rand; % Your calculations here
end
And when the exact number of required elements is not known in advance, allocate the maximum number of elements.
  댓글 수: 1
mustafa alnasser
mustafa alnasser 2014년 10월 6일
I have an array of two columns returned from function , i need to run this function inside loop and stores all arrays , how to do that?

댓글을 달려면 로그인하십시오.

카테고리

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