How do you use lsqcurvefit to fit a 2D function to a 2D array?
It's possible to reformulate the problem for lsqcurvefit, but why not use lsqnonlin directly, since lsqcurvefit is nothing but a wrapper for lsqnonlin?
Say you have arrays xx
, yy
, zz
, which define your 2D surface, such that surf(xx,yy,zz)
plots the surface.
Then you create a function objectiveFunction(params,xx,yy,zz)
that estimates zz
for at every coordinate as defined in xx
and yy
with parameters defined in params
, and that returns a vector of the difference between zz
and the function output.
Finally, you assign to the array initialGuess
some initial guess for the parameters, and you call lsqnonlin
like this:
estimatedParameters = lsqnonlin(@(params)objectiveFunction(params,xx,yy,zz),initialGuess)
You need to define what you mean by fitting a function to a 2-d array. Do you wish to fit some surface as a function of the row and column indices into that array?
If so, then generate the rectangular arrays of row and column indices using meshgrid. Now you can use them in your function. Pass them in directly to your objective function using a function handle. Don't forget to use the elementwise operators for multiplication (.*), division (./) and powers (.^) in your function.
The actual choice of model is your choice of course.
As for the use of lsqcurvefit (as opposed to lsqnonlin), they are essentially the same, but with a slightly different interface.