anonymous function vs local function or M-file function
Show older comments
Dear all, I have a code of curvefitting, it does not display the fitted results. If I replace the anonymous function by a local function (or a M-file function), it works. Would someone explain to me why?
function fitcurv(varargin)
xdata = [8.4 16.6 24.2 31.9 40 48.4];
ydata = [22.48 34.26 43.88 53.6 60.96 69.38];
fun=@(a,xdata) a(1)* xdata.^a(2);
[a,resnorm] = lsqcurvefit(fun,a0,xdata,ydata);
@[resnorm, a] = lsqcurvefit(@fun,a0,xdata,ydata) ;
% function f= fun(a,xdata)
% f=a(1)* xdata.^a(2);
% end
end
Answers (1)
Star Strider
on 31 May 2014
It works for me as an anonymous function:
xdata = [8.4 16.6 24.2 31.9 40 48.4];
ydata = [22.48 34.26 43.88 53.6 60.96 69.38];
a0 = [1 1';]
fun=@(a,xdata) a(1)* xdata.^a(2);
[a,resnorm] = lsqcurvefit(fun,a0,xdata,ydata);
yfit = fun(a,xdata);
figure(1)
plot(xdata, ydata, '+b')
hold on
plot(xdata, yfit, '-r')
hold off
grid
produces:
a =
5.5706e+000 650.0194e-003
resnorm =
880.7449e-003
and a good fit when plotted.
Categories
Find more on Function Creation 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!