MATLAB: Lsqcurvefit and anonymous function error

anonymous functionerrorlsqcurvefit

I'm trying to use lsqcurvefit with an anonymous function within the script to determine the best fit for a hyperbolic tangent function. However, I keep receiving the following error as outlined by the exception variable:
'Objective function is returning undefined values at initial point. lsqcurvefit cannot continue.'
Here is the code:
% Estimate hyperbolic tangent parameters using least squares curve fit.
xo = [ 15; 20; 15 ]; % initial guess of tangent curve parameters.
lb = [ 16; 0; 0 ]; ub = [ 17; 40; 40 ]; % Bounds for the parameters
d = 0:0.1:65;
hyper = @( c, rkm ) c( 1 ).*( 1 - tanh( ( rkm - c( 2 ) ./ c( 3 ) ) ) );
for n = 1:2%size( sal, 1 )
try
% Fit the hyperbolic tangent parameters using the least squares curve fit.
[ param, resnorm ] = lsqcurvefit( hyper, xo, rkm, sal(n,:), lb, ub );
BSo(n) = param(1);
Bxc(n) = param(2);
BxL(n) = param(3);
catch exception2
continue
end
end

Best Answer

You don’t give values for rkm or sal. When I created values for them, I had no problems with the following code (essentially yours, with a couple lines added to create the data):
xo = [ 15; 20; 15 ]; % initial guess of tangent curve parameters.
lb = [ 16; 0; 0 ]; ub = [ 17; 40; 40 ]; % Bounds for the parameters
hyper = @( c, rkm ) c( 1 ).*( 1 - tanh( ( rkm - c( 2 ) ./ c( 3 ) ) ) );
rkm = -10:2:10;
sal = [hyper([16.25 11 37],rkm); hyper([16.75 19 31],rkm)];
d = 0:0.1:65;
hyper = @( c, rkm ) c( 1 ).*( 1 - tanh( ( rkm - c( 2 ) ./ c( 3 ) ) ) );
for n = 1:2 %size( sal, 1 )
try
% Fit the hyperbolic tangent parameters using the least squares curve fit.
[ param, resnorm ] = lsqcurvefit( hyper, xo, rkm, sal(n,:), lb, ub );
BSo(n) = param(1);
Bxc(n) = param(2);
BxL(n) = param(3);
catch exception2
continue
end
end