Search code examples
matlabnonlinear-functions

solve a system of nonlinear equations in matlab


I'm trying to solve 4 nonlinear equations in matlab. i wrote a code using fsolve but it failed to proceed, and wrote another one using solve but after 4 hours of running without a result I stop it myself. I dont know what else i can use to solve it? is it solvable at all?

this is the code I wrote using fsolve x and y are vectors and n is the length of this vectors equal to 1200. nu is degree of freedom equal to 1196. p(1), p(2)... and p(4) are the unknowns

x = data1(:,1);
y = data1(:,2);
n = length(x);

p0 = [0 0 0 0];

options = optimset('Display','iter');
[p,fval] = fsolve(@myfunc,p0,options);

myfunc:

function F = myfunc(p)
global x y n

r = y-p(1)*x.^3-p(2)*x.^2-p(3)*x-p(4);

F = [sum(x.^3)-(n-4-2)*sum(x.^3./r);
     sum(x.^2)-(n-4-2)*sum(x.^2./r);
     sum(x.^1)-(n-4-2)*sum(x.^1./r);
     sum(x.^0)-(n-4-2)*sum(x.^0./r)];

Solution

  • Sounds like the problem is too stiff for fsolve, or you've got a poor starting guess. The code you have looks fine, however, if you may want to use a parametrized anonymous function:

    x = data1(:,1);
    y = data1(:,2);
    n = length(x);
    
    p0 = [0 0 0 0];
    
    options = optimset('Display','iter');
    [p,fval] = fsolve(@(p) myfunc(p,x,y,n),p0,options);
    

    then myfunc:

    function F = myfunc(p,x,y,n)
    
    r = y-p(1)*x.^3-p(2)*x.^2-p(3)*x-p(4);
    
    F = [sum(x.^3)-(n-4-2)*sum(x.^3./r);
         sum(x.^2)-(n-4-2)*sum(x.^2./r);
         sum(x.^1)-(n-4-2)*sum(x.^1./r);
         sum(x.^0)-(n-4-2)*sum(x.^0./r)];
    end