我有一堆我希望适合函数的数据:
除x
之外的所有变量都必须合适。你能帮我解决这个问题吗?
答案 0 :(得分:4)
您可以使用curve-fitting by optimization查找参数a
,b
,w
和x_c
:
创建一个目标函数sseval()
,其中包含您希望适合作为目标的函数:
function sse = sseval(para, xdata, ydata)
% Set up the function parameters:
a = para(1);
b = para(2);
w = para(3);
x_c = para(4);
% Compute the target function (what you want to fit to):
funct = (b*(w/2)^2 - a*(w/2)*(xdata - x_c)) ./ ((xdata - x_c).^2 + (w/2)^2).^2;
% Return the sum of squared errors for the given set of data:
sse = sum((ydata - funct).^2);
end
然后使用fminsearch()
查找您的参数:
% Start off with a random set of parameters:
para0 = rand(4, 1);
% Create a handle to function 'sseval()' ('xdata' and 'ydata' correspond to
% variable 'x' and the data that you want to fit to the function, respectively):
funct = @(para)sseval(para, xdata, ydata);
% Find the best parameters that fit the target function:
best_para = fminsearch(funct, para0);
要查看参数的拟合程度,可以在数据顶部绘制拟合曲线:
% Set up the function parameters:
a = best_para(1);
b = best_para(2);
w = best_para(3);
x_c = best_para(4);
% Compute the target function using the fitted parameters:
yfit = (b*(w/2)^2 - a*(w/2)*(xdata - x_c)) ./ ((xdata - x_c).^2 + (w/2)^2).^2;
% Plot the data along with the fitted curve:
plot(xdata, ydata, '*');
hold on
plot(xdata, yfit, 'r');
xlabel('xdata')
ylabel('Data and Fitted Curve')
title('Data and Best Fitting Curve')
legend('Data', 'Fitted Curve')
hold off