How do I save this loop output into an array?

9 Ansichten (letzte 30 Tage)
Edivaldo Bartolomeu
Edivaldo Bartolomeu am 17 Feb. 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

Akzeptierte Antwort

KALYAN ACHARJYA
KALYAN ACHARJYA am 17 Feb. 2021
Bearbeitet: KALYAN ACHARJYA am 17 Feb. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by