我想我已经解决了这个问题,但是如何将每个迭代的x
值从fzero
上传到列矩阵中?我已经使用二分法找到零,结果似乎匹配。
当我运行代码时:
% second part
clear all; close all;
x= 100:0.01:200; % domain
f = @(x) sqrt((x*9.8)/0.25)* tanh(sqrt((0.25 * 9.8) / x) * 4) - 36;
%x02 = fzero(f, 100, optimset('Tolx', 1*e*(-6))) % What's the point
%of this?
x03 = fzero(f, 100, optimset('Display', 'iter')) % 100 is initial starting point
我明白了:
Search for an interval around 100 containing a sign change:
Func-count a f(a) b f(b) Procedure
1 100 -1.22895 100 -1.22895 initial interval
3 97.1716 -1.34001 102.828 -1.12319 search
5 96 -1.38767 104 -1.08085 search
7 94.3431 -1.45679 105.657 -1.02236 search
9 92 -1.55819 108 -0.942334 search
11 88.6863 -1.70937 111.314 -0.834198 search
13 84 -1.94034 116 -0.690568 search
15 77.3726 -2.30675 122.627 -0.504071 search
17 68 -2.92417 132 -0.268914 search
19 54.7452 -4.07851 145.255 0.0168687 search
Search for a zero in the interval [54.7452, 145.255]:
Func-count x f(x) Procedure
19 145.255 0.0168687 initial
20 144.882 0.00947591 interpolation
21 144.405 -2.82264e-05 interpolation
22 144.407 8.38448e-08 interpolation
23 144.407 7.4607e-13 interpolation
24 144.407 -1.42109e-14 interpolation
25 144.407 0 interpolation
Zero found in the interval [54.7452, 145.255]
x03 =
144.4067
与使用二分法的144.4092类似地进行比较。另外,我试图将容差设置为10(-6),但我无法让它工作,我做错了什么?或者我接近这一切都错了?
答案 0 :(得分:1)
我的猜测是,该问题要求您复制并粘贴fzero
的'Display'
选项的输出。然而,这种蹩脚的,复制和粘贴数据是一个不好的习惯,结果只有几个小数位的精度。您可以使用output function和'OutputFcn'
option执行此操作,但这有点像黑客。
f = @(x)sqrt((x*9.8)/0.25)*tanh(sqrt((0.25*9.8)./x)*4)-36;
global xout fout;
opts = optimset('Display', 'iter', 'TolX', 1e-6, 'OutputFcn', @outfun);
[x0, f0, exitflag] = fzero(f, 100, opts)
xout
fout
其中outfun
是子函数(或单独的M文件),定义为:
function stop = outfun(x, optVals, state)
stop = false;
global xout fout;
switch(state)
case 'init'
xout = x;
fout = optVals.fval;
case 'iter'
if ~strcmp(optVals.procedure,'search')
xout = [xout;x];
fout = [fout;optVals.fval];
end
otherwise
end
当然还有其他方法可以实现这一点,可能还有一些方法可以避免使用global
。另请注意,在fzero
的搜索阶段(根包围)期间,我没有输出状态,因为向量将是常量。