How do I save this loop output into an array?
9 views (last 30 days)
Show older comments
Edivaldo Bartolomeu
on 17 Feb 2021
Commented: Edivaldo Bartolomeu
on 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
0 Comments
Accepted Answer
KALYAN ACHARJYA
on 17 Feb 2021
Edited: KALYAN ACHARJYA
on 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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!