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

7 visualizaciones (últimos 30 días)
Anna
Anna el 4 de Ag. de 2013
Comentada: mustafa alnasser el 6 de Oct. de 2014
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 comentario
Jan
Jan el 4 de Ag. de 2013
Editada: Jan el 4 de Ag. de 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.

Iniciar sesión para comentar.

Respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 4 de Ag. de 2013
Editada: Azzi Abdelmalek el 4 de Ag. de 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 comentario
Jan
Jan el 4 de Ag. de 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.

Iniciar sesión para comentar.


Jan
Jan el 4 de Ag. de 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 comentario
mustafa alnasser
mustafa alnasser el 6 de Oct. de 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?

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by