0

I have a question about using the lsqnonlin function.

In my case I have two functions:

f_1=@(t,x)sin(t+x.^2);
f_2=@(t,x)cos(x.^2)+3.*t.^2;
f = {f_1, f_2};

I want to find the values of the arguments t and x which would result in the least square error, defined as: f_1(t,x)^2+f_2(t,x)^2. In other words, argmin for LSE.

My code is as follow with initial guess [1,2]:

lsqnonlin(f,[1,2])

And I'm getting the error:

Error in lsqnonlin (line 196)
        initVals.F = feval(funfcn{3},xCurrent,varargin{:});
Caused by:
Failure in initial objective function evaluation. LSQNONLIN cannot continue.

lsqnonlin can be used for vector function and vector input according to the documentation. I wonder how to prepare corresponding codes for it. Could anyone suggest the solution?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
will_cheuk
  • 379
  • 3
  • 12

1 Answers1

0

You are getting an error because lsqnonlin expects a scalar function handle that maps a vector to a vector, whereas you specify a cell array of function handles. To fix this, instead of a vector of functions outputting one scalar each, you need to rewrite it into a single function that accepts a vector of inputs and also outputs a vector:

f = @(xt)[sin(xt(2)+xt(1).^2), cos(xt(1).^2)+3.*xt(2).^2];    
% xt = [x,t]   
% f = [f_1(xt), f_2(xt)]

so f and xt are both vectors of 2 elements.

Then, the solver works:

lsqnonlin(f,[1,2])

ans =

    1.6144    0.5354
Dev-iL
  • 23,742
  • 7
  • 57
  • 99