我编写了一个python函数来获取以下余弦函数的参数:
param = Parameters()
param.add( 'amp', value = amp_guess, min = 0.1 * amp_guess, max = amp_guess )
param.add( 'off', value = off_guess, min = -10, max = 10 )
param.add( 'shift', value = shift_guess[0], min = 0, max = 2 * np.pi, )
fit_values = minimize( self.residual, param, args = ( azi_unique, los_unique ) )
def residual( self, param, azi, data ):
"""
Parameters
----------
Returns
-------
"""
amp = param['amp'].value
off = param['off'].value
shift = param['shift'].value
model = off + amp * np.cos( azi - shift )
return model - data
在Matlab中如何获得余弦函数的幅度,偏移和偏移?
答案 0 :(得分:5)
我的经验告诉我,总是很好地依赖于工具箱。对于您的特定情况,模型很简单,手动操作非常简单。
假设您有以下型号:
y = B + A*cos(w*x + phi)
并且您的数据间隔相等,然后:
%// Create some bogus data
A = 8;
B = -4;
w = 0.2;
phi = 1.8;
x = 0 : 0.1 : 8.4*pi;
y = B + A*cos(w*x + phi) + 0.5*randn(size(x));
%// Find kick-ass initial estimates
L = length(y);
N = 2^nextpow2(L);
B0 = (max(y(:))+min(y(:)))/2;
Y = fft(y-B0, N)/L;
f = 5/(x(2)-x(1)) * linspace(0,1,N/2+1);
[A0,I] = max( 2*abs(Y(1:N/2+1)) );
w0 = f(I);
phi0 = 2*imag(Y(I));
%// Refine the fit
sol = fminsearch(@(t) sum( (y(:)-t(1)-t(2)*cos(t(3)*x(:)+t(4))).^2 ), [B0 A0 w0 phi0])
结果:
sol = %// B was -4 A was 8 w was 0.2 phi was 1.8
-4.0097e+000 7.9913e+000 1.9998e-001 1.7961e+000
答案 1 :(得分:4)
MATLAB在优化工具箱中有一个名为lsqcurvefit
的函数:
lsqcurvefit(fun,X0,xdata,ydata,lbound,ubound);
其中fun
是要拟合的函数,x0
是初始参数guess,xdata和ydata是不言自明的,lbound和ubound是参数的下限和上限。因此,例如,您可能有一个函数:
% x(1) = amp
% x(2) = shift
% x(3) = offset
% note cosd instead of cos, because your data appears to be in degrees
cosfit = @(x,xdata) x(1) .* cosd(xdata - x(2)) + x(3);
然后您将按如下方式调用lsqcurvefit函数:
guess = [7,150,0.5];
lbound = [-10,0,-10]
ubound = [10,360,10]
fit_values = lsqcurvefit(cosfit,guess,azi_unique,los_unique,lbound,ubound);