How do I save this loop output into an array?

9 visualizaciones (últimos 30 días)
Edivaldo Bartolomeu
Edivaldo Bartolomeu el 17 de Feb. de 2021
Comentada: Edivaldo Bartolomeu el 17 de Feb. de 2021
Hi everybody
I am having trouble saving the loop outputs from the variable ESTIMATE into an array.
The code is below:
%% Question 5: Saving Results from Iterative Equations in an Array
clear
clc
o_number = input('Enter the original number: ');
estimate = input('Enter the initial estimate: ');
error = abs(o_number - estimate^3);
iterations = 0;
while (error >= 1e-9)
estimate = 1/3*(2*estimate + o_number/estimate^2); % outputs to be saved in a 1-d array.
error = abs(o_number - estimate^3);
iterations = iterations + 1;
end

Respuesta aceptada

KALYAN ACHARJYA
KALYAN ACHARJYA el 17 de Feb. de 2021
Editada: KALYAN ACHARJYA el 17 de Feb. de 2021
Use as array
estimate=[];
o_number = input('Enter the original number: ');
estimate(1)= input('Enter the initial estimate: ');
error= abs(o_number - estimate^3);
iter=1;
while (error >= 1e-9)
estimate(iter+1) = 1/3*(2*estimate(iter) + o_number/estimate(iter)^2);
error= abs(o_number - estimate(iter+1)^3);
iter= iter + 1;
end
Note that here extact size of preallocation of the vectors are not possible, because no idea about number of iterations. In such case either you choose the huge array size and later crop the array based on last iter value.

Más respuestas (0)

Categorías

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

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by