我有一个数据数组,当绘制时,看起来像wave.I需要确定这些数据的最佳拟合(线性和指数),并在此函数中找到lambda 1,lambda 2和tau的值((L = lambda 1 * t + lambda 2 *(1-exp(-t / tau)。 有些朋友建议我使用((polyfit))但在阅读帮助文件和在Google中搜索后,我无法理解命令的适用性。任何帮助将不胜感激。我将感激你。
我的尝试如下:
%% data 1
file1 = dlmread('outfile_rate_add0.5_depGDP_GTP0.1.txt');
t1 = file1 (:,1);
d1 = file1 (:,2);
% Then call plot()
plot(t1, d1, 'b*-', 'LineWidth', 2, 'MarkerSize', 15);
% Then get a fit
coeffs1 = polyfit(t1, d1, 1)
% Get fitted values
fittedX1 = linspace(min(t1), max(t1), 1001);
fittedY1 = polyval(coeffs1, fittedX1);
% Plot the fitted line
hold on;
plot(fittedX1, fittedY1, 'r-', 'LineWidth', 3);
hold off
hleg = legend('Data','lam*t + c','Location','northEast');
grid on;
title('Line fitting ','fontsize',13,'fontweight','b','color','k')
xlabel('Time ms','fontsize',13,'fontweight','b','color','k');
ylabel('Averge length','fontsize',13,'fontweight','b','color','k');
答案 0 :(得分:3)
如果您可以访问优化工具箱,则可以制定此问题,以便可以使用fminsearch()解决此问题。以下是它的完成方式: 要优化的参数(lambda1,lambda2和tau)存储在一个参数向量中,fit_function将使用该参数向量,这是您提出的函数。
function main
% some data
t = sort(rand(50,1)*10);
lambda1 = 0.5;
lambda2 = 1;
tau = 2.0;
par = [lambda1, lambda2, tau];
y = fit_function(t, par) + (rand(size(t))-0.5)*0.2;
par0 = [1,2,3]; % initial guess
par_fit = fminsearch(@objFun, par0);
% nested objective function, this one will be minimized
function e = objFun(par)
yfitted = fit_function(t, par);
e = sum((yfitted-y).^2);
end
% plotting some results
figure
plot(t,fit_function(t,par),'k-')
hold on
plot(t,y,'ko')
plot(t,fit_function(t,par_fit),'rx-')
legend('original','noisy','optimization')
par
par_fit
end
function yfitted = fit_function(t, par)
% y = lambda1*t + lambda2*(1-exp(-t/tau))
lambda1 = par(1);
lambda2 = par(2);
tau = par(3);
yfitted = lambda1*t + lambda2*(1-exp(-t/tau));
end
结果如下: 我用于unnoisy数据的参数和从优化中得出的参数就像这样
par =
0.5000 1.0000 2.0000
par_fit =
0.4949 1.0433 2.1792
Best,Nras。
更新您的用例
function main
%% ----- DATA -----
file1 = dlmread('outfile_rate_add0.5_depGDP_GTP0.1.txt');
t = file1(:,1);
y = file1(:,2);
%% ----- OPTIMIZATION -----
par0 = [1,2,3]; % initial guess <--- Here you have to make a good guess
par_fit = fminsearch(@objFun, par0);
%% ----- OBJECTIVE FUNCTION (will be minimized) -----
function e = objFun(par)
yfitted = fit_function(t, par); % result of model function with current parameter
e = sum((yfitted-y).^2); % minimize squared distance between model and observation
end
%% ----- VSIUALIZING RESULTS ----- %
figure
plot(t,y,'ko')
hold on
plot(t,fit_function(t,par_fit),'rx-')
legend('original','optimization')
end
%% ----- MODEL FUNCTION ----- %
function yfitted = fit_function(t, par)
% the model function reads as: y = lambda1*t + lambda2*(1-exp(-t/tau))
lambda1 = par(1);
lambda2 = par(2);
tau = par(3);
yfitted = lambda1*t + lambda2*(1-exp(-t/tau));
end