Code covered by the BSD License  

Highlights from
newt

image thumbnail
from newt by Gabriel Frangakis
This function quickly preforms Newton's method on a vector function of multiple variables.

newt(er,varargin)
function [sol] = newt(er,varargin)
%NEWT A function that preforms Newton's method
%   This function preforms Newton's method on a variable number of
%   equations. Enter the variable name as a string, then an initial guess,
%   then the functions in order.
%   Written by Gabe Frangakis, 2010.
%
%   The first input of newt must be the tolerance you desire. This must be
%   a non-negative real number. The next inputs must be variables,
%   equations, and guesses. There is no requirement for which order these
%   are entered in, only that the order of variables and the order of
%   guesses are the same. For example, if you enter your variables in the
%   order y,z,x, your guesses must be entered as y guess, z guess, and x
%   guess. Variables and equations must be entered as strings. Equations
%   should be written explicitly i.e. instead of 2x^2, you write 2*x^2.
%% Initialize
guesscount=0;
eqcount=0;
optarg=size(varargin);
optarg=optarg(:,2);
varlist=[];
eqlist=[];
ber=0;
format long
%% Separate the Arguments
for k=1:optarg
    mat=cell2mat(varargin(k));
    str=isa(mat,'char');
    dble=isa(mat,'double');
    if str==1
        l=length(mat);
        if l==1
            syms(mat)
            varlist=[varlist;mat];%is a variable
        else
            eqcount=eqcount+1;
            eqlist=[eqlist;sym(mat)];
        end
    end
    if dble==1
        l=length(mat);
        if l==1
        guesscount=guesscount+1;
        guess(guesscount,1)=mat;
        else
            eqcount=eqcount+1;
            var=varlist(eqcount);
            str1=poly2str(mat,var);
            eqlist=[eqlist;sym(str1)];
        end
    end
end
%% Make everything check out
%  Number of variables must equal number of equations must equal number of
%  guesses
if guesscount~=size(varlist,1)|guesscount~=eqcount
    error('newt:argChk', 'Number of varibles, initial guesses, and equations must be equal')
end
%% Execute Newton's method
xo=guess;
%Evaluate the Jacobian and F(x).
while ber==0
    jacob=jacobian(eqlist);
    fxo=eqlist;
    for j=1:eqcount
        jacob=subs(jacob,varlist(j),xo(j)); %sub into the Jacobian
        fxo=subs(fxo,varlist(j),xo(j)); %find F(xo)
    end
    h=linsolve(jacob,-fxo); %solve Jacob.h=-F(xo)
    xo=xo+h;
    if abs(fxo)<=er
        ber=1;
    end
end
sol=xo;
end


Contact us