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

7 views (last 30 days)
Anna
Anna on 4 Aug 2013
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 Comment
Jan
Jan on 4 Aug 2013
Edited: Jan on 4 Aug 2013
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.

Sign in to comment.

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 4 Aug 2013
Edited: Azzi Abdelmalek on 4 Aug 2013
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 Comment
Jan
Jan on 4 Aug 2013
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.

Sign in to comment.


Jan
Jan on 4 Aug 2013
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 Comment
mustafa alnasser
mustafa alnasser on 6 Oct 2014
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?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!