Azzera filtri
Azzera filtri

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

3 visualizzazioni (ultimi 30 giorni)
Anna
Anna il 4 Ago 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 Commento
Jan
Jan il 4 Ago 2013
Modificato: Jan il 4 Ago 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.

Accedi per commentare.

Risposte (2)

Azzi Abdelmalek
Azzi Abdelmalek il 4 Ago 2013
Modificato: Azzi Abdelmalek il 4 Ago 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 Commento
Jan
Jan il 4 Ago 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.

Accedi per commentare.


Jan
Jan il 4 Ago 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 Commento
mustafa alnasser
mustafa alnasser il 6 Ott 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?

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by