Newton Raphsons method in Matlab?

后端 未结 3 1273
轻奢々
轻奢々 2020-12-11 13:45

Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don\'t get if I can pass a function to a function and how to use the de

3条回答
  •  遥遥无期
    2020-12-11 14:07

    There's no way to algebraically take derivatives of function handles or functions defined in m-files. You would have to do this numerically by evaluating the function at a number of points and approximating the derivative.

    What you're probably wanting to do is differentiation of symbolic equations, and you need the Symbolic Math Toolbox for that. Here's an example of finding a root using the Newton-Raphson method:

    >> syms x            %# Create a symbolic variable x
    >> f = (x-4)^2-4;    %# Create a function of x to find a root of
    >> xRoot = 1;        %# Initial guess for the root
    >> g = x-f/diff(f);  %# Create a Newton-Raphson approximation function
    >> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the initial guess
    
    xRoot =
    
        1.8333
    
    >> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess
    
    xRoot =
    
        1.9936
    
    >> xRoot = subs(g,'x',xRoot)  %# Evaluate the function at the refined guess
    
    xRoot =
    
        2.0000
    

    You can see that the value of xRoot comes close to the value of the true root (which is 2) after just a couple of iterations. You could also place the function evaluation in a while loop with a condition that checks how big a difference there is between each new guess and the previous guess, stopping when that difference is sufficiently small (i.e. the root has been found):

    xRoot = 1;                     %# Initial guess
    xNew = subs(g,'x',xRoot);      %# Refined guess
    while abs(xNew-xRoot) > 1e-10  %# Loop while they differ by more than 1e-10
      xRoot = xNew;                %# Update the old guess
      xNew = subs(g,'x',xRoot);    %# Update the new guess
    end
    xRoot = xNew;                  %# Update the final value for the root
    

提交回复
热议问题