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

3 次查看(过去 30 天)
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