Search code examples
matlabnumerical-methodsnonlinear-functionsnewtons-method

I can't see the output of my Matlab code for Newton's Method, what am I missing?


So I have the following matlab code where I am attempting to calculate Newton's Method to solve a non-linear equation (in particular, identify the square root). I am unable to see the output of my two fprintf() statements, so I think I fundamentally misunderstand MATLAB's way of calling functions.

I feel that there is something so fundamentally basic that I missing here.

I am running this over the Matlab web application https://matlab.mathworks.com/

My code is the following:

clear all
p = 81; %set to whatever value whose square root you want to find.
egFun = @ (x) x^2 - p;
egFunDer = @ (x) 2*x;
firstGuess = p;
Err = 0.00001;
imax = 20;

%% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
    for i = 1 : imax
        fprintf("test %f", i)
        % below is the newton's method formula in action
        Xi = Xest - Fun(Xest)/FunDer(Xest)
        % let Xest be replaced with our new value for X so that we can
        % perform the next iteration
        if(abs(0-Fun(Xi)) <= Err)
            Xsolution = Xi;
            break
        end
        Xest = Xi
    end
    Xsolution = Xi;
end
%%
function answer = main
    answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
    fprintf("the Solution is %f", answer)
end

I expect to see a value for answer, which should print to the console, as well as the two fprintf() statements I threw in for debugging.


Solution

  • You need to call NewtonRoot function in main code.

    clear all
    p = 81; %set to whatever value whose square root you want to find.
    egFun = @ (x) x^2 - p;
    egFunDer = @ (x) 2*x;
    firstGuess = p;
    Err = 0.00001;
    imax = 20;
    %% 
    answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
    fprintf("the Solution is %f", answer)
    
    %% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
    function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
        for i = 1 : imax
            fprintf("test %f", i)
            % below is the newton's method formula in action
            Xi = Xest - Fun(Xest)/FunDer(Xest)
            % let Xest be replaced with our new value for X so that we can
            % perform the next iteration
            if(abs(0-Fun(Xi)) <= Err)
                Xsolution = Xi;
                break
            end
            Xest = Xi
        end
        Xsolution = Xi;
    end