how I use function F = myfun1(x,xdata) F= @(x,xdata)​x(1).*exp(​x(2).*xdat​a);

5 views (last 30 days)
function F = myfun1(x,xdata)
F= @(x,xdata)x(1).*exp(x(2).*xdata);
% Assume you determined xdata and ydata experimentally
xdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
ydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];
x0 = [100, -1]; % Starting guess
x = lsqcurvefit(@myfun1,x0,xdata,ydata);
Error: Failure in initial objective function evaluation. LSQCURVEFIT cannot continue.

Answers (1)

Rajanya
Rajanya on 1 Jul 2025
The following line makes 'F' a function handle to an anonymous function-
F= @(x,xdata)x(1).*exp(x(2).*xdata);
However, 'lsqcurvefit' expects a vector of values (see here), and hence it cannot continue.
Changing the function definition of 'myfun1' to the following returns a vector of predicted values-
function F = myfun1(x,xdata)
F = x(1).*exp(x(2).*xdata);
end
Then, the error is resolved.
xdata = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
ydata = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];
x0 = [100, -1]; % Starting guess
x = lsqcurvefit(@myfun1,x0,xdata,ydata);
Local minimum possible. lsqcurvefit stopped because the final change in the sum of squares relative to its initial value is less than the value of the function tolerance.
x
x = 1×2
498.8309 -0.1013
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
To learn more about anonymous functions and how they are used, you can refer to its documentation by executing the following command from MATLAB Command Window-
doc Anonymous Functions
Thanks!

Categories

Find more on Matrix Computations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!