Search code examples
matlabsymbolic-math

Newton Raphson method problem when iterating a variable


I need help with a problem. I written a program to calculate the value of a function using the Newton Raphson method. However, the function also has a variable i would like to iterate over, V. The program runs fine until the second iteration of the outer for loop, then the inner for loop will not run further once it reaches the Newton Raphson function. If someone has any ideas of what is wrong, I would greatly appreciate it. The error i get is: Warning: Solution does not exist because the system is inconsistent.

The code is below for detail.


for V = 1:50;

syms x;

f(V)= Il-x-Is.*(exp((q.*(V+x.*Rs))./(1000.*y.*K.*T))-1)-((V+x.*Rs)./Rsh); 

g(V)=diff(f(V)); 

x0 = 0;

i = 1;

for i=1:10

        f0=vpa(subs(f,x,x0)); 

        f0_der=vpa(subs(g,x,x0)); 

        y=x0-f0/f0_der; % Newton Raphson

        x0=y;
end
end

Solution

  • Assuming you have a function defined like

    func = @(x,V) V+x+exp(x);
    

    There are plenty of options that avoid expensive symbolic calculations.

    Firstly, making a vector of values of x0 using fzero and a for loop:

    for V = 1:50
        x0(V) = fzero(@(x) func(x,V),0);
    end
    

    Secondly, the same thing again but written as an anonymous function, so you can call x0(1.5) or x0(1:50):

    x0 = @(V) arrayfun(@(s) fzero(@(x) func(x,s),0),V);
    

    Finally, if you want to use ten steps of Newton's method and calculate the derivative symbolically (although this is not a great method),

    syms y Vsym
    g = matlabFunction(diff(func(y,Vsym),y),'Vars',[y Vsym]);
    
    for V = 1:50
        x0(V) = 0;
        for i = 1:10
            x0(V) = x0(V)-func(x0(V),V)/g(x0(V),V); % Newton Raphson
        end
    end
    

    Which at least will be more efficient in the loops because it's just using anonymous functions.