【问题标题】:Table from a function with while loop [MATLAB]来自带有 while 循环的函数的表 [MATLAB]
【发布时间】:2021-11-14 15:07:24
【问题描述】:

我编写了一个代码,它在函数间隔中给了我一个零。这段代码使用了牛顿法和二分法相结合的方法。

这是我的代码,

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 文件中创建一个表,其中包含每次迭代的输出 {用于每个迭代(牛顿或二分法)、a、b、p、f(p)} 的方法,我应该添加什么?

我可以在命令窗口中获得所需的数据(使用下面的代码),但我无法使用 Matlab 制作实际表格。

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

我能得到一些帮助吗?

【问题讨论】:

    标签: matlab datatable


    【解决方案1】:

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

    • 预先分配您的表(出于性能目的,请参阅doc Preallocation
    • 将每次迭代的对应值添加到表中
    • 删除剩余行并将表存储到 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
    

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 2015-05-24
      • 2012-10-27
      • 2015-07-17
      • 2014-02-17
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多