2

我写了一个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 中如何获得余弦函数的幅度、偏移和偏移?

4

2 回答 2

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    
于 2013-10-22T12:49:57.783 回答
4

MATLAB 有一个lsqcurvefit在优化工具箱中调用的函数:

lsqcurvefit(fun,X0,xdata,ydata,lbound,ubound);

其中fun是要拟合的函数,x0是初始参数猜测值,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);
于 2013-10-22T10:17:59.493 回答