How to output the answer to a while loop into an array

31 次查看(过去 30 天)
I have the following code that is supposed to stop once h>1e-13, the problem that I am running into though is that the answer is supposed to be input into an array but I can't figure out how I am supposed to do that because I just keep getting an answer that is a single digit rather than an array with all of the values for h that where calculated this way.
h(1)=1;
hnew=h/2;
while hnew>=1e-13;
h=hnew;
hnew=h/2;
end
The code works like it is supposed to, but I just need to find out how to add each one of the iterations for h into an array

回答(1 个)

Voss
Voss 2022-2-3
Maybe this is what you are going for:
h(1) = 1;
hnew = h/2;
while hnew >= 1e-13
h(end+1) = hnew;
hnew = h(end)/2;
end
disp(h);
Columns 1 through 22 1.0000 0.5000 0.2500 0.1250 0.0625 0.0312 0.0156 0.0078 0.0039 0.0020 0.0010 0.0005 0.0002 0.0001 0.0001 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 Columns 23 through 44 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
disp(hnew);
5.6843e-14

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by