简体   繁体   中英

Fitting data to a known function MATLAB (without curve fitting toolbox)

I have a function with three parameters and some data that I want to fit. How can I do this optimally? I am not even sure of the range of the three parameters in the equation.

The function has free parameters alpha , beta and gamma and is given by

 y = (1 - alpha + alpha./sqrt(1 + 2*beta*(gamma*x).^2./alpha)).^(-1) - 1;

I have arrays of x and y data points (around 50 points in each set) to which I want to find the best fit (defined as minimizing least squares) using any alpha , beta and gamma .

The solutions online recommend the curve fitting toolbox, which I do not have on my machine and am unable to install. I only have the barebones MATLAB 2015b version.

You need an optimization algorithm for smooth, R^n -> R functions. Since you have only access to barebone Matlab, a good idea is to take an algorithm from File Exchange. For illustration I picked LMFnlsq , which should suffice since you have a small problem, although it seems to be more general and a little bit overkill here.

Download LMFnlsq and add to your Matlab path.


Example

For convenience make a function called regr_fun :

function y = regr_fun(par, x)
    alpha   = par(1);
    beta    = par(2);
    gamma   = par(3); 
    y = (1 - alpha + alpha./sqrt(1 + 2*beta*(gamma*x).^2./alpha)).^(-1) - 1;
end

Curve fitting (in the same folder as regr_fun ):

%---------------------------------------------------------------------
% DUMMY DATA
%---------------------------------------------------------------------
% Generate data from known model contaminated with random noise
rng(333) % for reproducibility

alpha   = 2;
beta    = 0.1;
gamma   = 0.1;
par     = [alpha, beta, gamma];

xx      = 1:50;
y_true  = regr_fun(par, xx);
yy      = y_true + normrnd(0,1,1,50);

%---------------------------------------------------------------------
% FIT MODEL
%---------------------------------------------------------------------
% intial point of solver
p0      = [1,1,1];

obj_fun = @(p) sum((regr_fun(p, xx) - yy).^2);

% optimization
p_fit   = LMFnlsq(obj_fun, p0);

y_fit   = regr_fun(p_fit, xx);

%---------------------------------------------------------------------
% PLOT
%---------------------------------------------------------------------
plot(xx, yy, 'o')
hold on
plot(xx, y_true)
plot(xx, y_fit, '--')

在此处输入图片说明


Note

Although matlab.codetools.requiredFilesAndProducts lists the symbolic toolbox as well, for this problem it is not needed and the function should run withouth that as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM