How do I save this loop output into an array?

9 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

KALYAN ACHARJYA
KALYAN ACHARJYA il 17 Feb 2021
Modificato: KALYAN ACHARJYA il 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.

Più risposte (0)

Categorie

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

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by