How do I save this loop output into an array?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
KALYAN ACHARJYA
2021-2-17
编辑:KALYAN ACHARJYA
2021-2-17
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!