Search code examples
matlaboptimizationleast-squares

Fsolve with variables,


I have this matlab function,

function [f]=ErrorFun(a,b,c)
    global I     
    global phi

    f = sum((a+b.*cos(phi)+c.*sin(phi)-I).^2);
end

length(a)=length(b)=length(phi)=length(c)=length(I)N.I want to use fsolve, but I don't know how to do it. ErrorFun is a least squares problem.


Solution

  • The documentation says

    X = fsolve(FUN,X0) starts at the matrix X0 and tries to solve the equations in FUN. FUN accepts input X and returns a vector (matrix) of equation values F evaluated at X.

    so you need to rewrite your function so that it accepts a single vector of parameters as its input. E.g., in your case,

    function f = ErrorFun(x)
        global I phi
        n = length(phi) ;
        a = x(1:n) ;
        b = x(n+1:2*n) ;
        c = x(2*n+1:3*n) ;
    
        f = sum((a+b.*cos(phi)+c.*sin(phi)-I).^2) ;
    end
    

    then call fsolve with this function and some initial vector x0 = [a; b; c].