Table 来自带有 while 循环的函数 [MATLAB]

Table from a function with while loop [MATLAB]

我写了一段代码,它在一个函数区间中给出了一个零。此代码使用了牛顿法和二分法的组合方法。

这是我的代码,

function p = newtonbisection(f, df, a, b, tol)
p = a;
while abs(f(p)) >= tol
if a <= p && b<= p
    p = p - f(p)/df(p);
else
    p = (a+b)/2;
end
if f(p)*f(b)<0
    a = p;
else 
    b = p;
end
end
end

我已经测试了这段代码并且工作正常。但是,如果我想在 .txt 文件中创建一个 table,每次迭代输出 {method that is used for each iter (Newton or bisection), a, b, p, f(p)},应该怎么办我需要添加吗?

我可以在命令 window 中获得所需的数据(使用下面的代码),但是我在使用 Matlab 制作实际的 table 时遇到了问题。

function p = newtonbisection(f, df, a, b, tol)
p = a;
iter = 0;
while abs(f(p)) >= tol
if a <= p && b<= p
    p = p - f(p)/df(p);
    iter = iter+1;
    fprintf("newton\n")
else
    p = (a+b)/2;
    iter = iter+1;
    fprintf("bisection\n")
end
if f(p)*f(b)<0
    a = p;
else 
    b = p;
end
iter
a 
b
p
disp(f(p))
end
end

我能得到一些帮助吗?

有多种方法可以做到这一点。一个简单的方法是:

  • 预分配您的 table(出于性能目的,参见 doc Preallocation
  • 将每次迭代的相应值添加到 table
  • 删除剩余的行并将 table 存储到 txt 文件

示例:

function p = newtonbisection(f, df, a, b, tol)
p = a;
iter = 0;

noRowsPreAll = 1000000;
sz = [noRowsPreAll 6];
varTypes = {'int32','categorical','double','double','double','double'};
varNames = {'step', 'method', 'a', 'b', 'p','f(p)'};
T = table('Size',sz,'VariableTypes',varTypes,'VariableNames', varNames);

while abs(f(p)) >= tol
    iter = iter+1;
    if iter > noRowsPreAll
        disp('Warning: preallocate a bigger table!')
    end
    T.step(iter) = iter;
    
    if a <= p && b<= p
        p = p - f(p)/df(p);
        T.method(iter) = 'newton';
    else
        p = (a+b)/2;
        T.method(iter) = 'bisection';
    end
    if f(p)*f(b)<0
        a = p;
    else
        b = p;
    end
    
    T.a(iter) = a;
    T.b(iter) = b;
    T.p(iter) = p;
    T.("f(p)")(iter) = f(p);
end

T(iter+1:end,:) = [];
writetable(T, 'output.txt')
end