Search code examples
matlabdatatable

Table from a function with while loop [MATLAB]


I've written a code that gives me a zero in an interval of functions. This code uses the combination method of Newton's and Bisection methods.

Here's my code,

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

I've tested this code and works fine. However, if I want to create a table in .txt file with outputs {method that is used for each iter (Newton or bisection), a, b, p, f(p)} from each iteration, what should I need to add?

I could get desired data that I need in the command window (with the code below), but I'm having trouble with making an actual table with 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

Can I get some help?


Solution

  • There are multiple ways to do this. A simple approach would be:

    • preallocate your table (for performance purposes, cf. doc Preallocation)
    • add the corresponding values for each iteration to the table
    • delete remaining rows and store the table to a txt file

    Example:

    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