MATLAB 中的曲线拟合如 1+x/1+x^2

Curve fit in MATLAB like 1+x/1+x^2

我有一堆数据要适合一个函数:

x 之外的所有变量都必须适合。你能帮我解决这个问题吗?

您可以使用 curve-fitting by optimization 来查找参数 abwx_c:

创建一个 objective 函数 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