Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何拟合余弦函数?_Matlab_Optimization_Numpy_Curve Fitting - Fatal编程技术网

Matlab 如何拟合余弦函数?

Matlab 如何拟合余弦函数?,matlab,optimization,numpy,curve-fitting,Matlab,Optimization,Numpy,Curve Fitting,我编写了一个python函数来获取以下余弦函数的参数: 在Matlab中,如何获得余弦函数的振幅、偏移和移位?Matlab在优化工具箱中有一个名为lsqcurvefit的函数: lsqcurvefit(fun,X0,xdata,ydata,lbound,ubound); 其中,fun是要拟合的函数,x0是初始参数猜测,xdata和ydata是自解释的,lbound和ubound是参数的上下限。例如,您可能有一个函数: % x(1) = amp % x(2) = shift % x(3) =

我编写了一个python函数来获取以下余弦函数的参数:


在Matlab中,如何获得余弦函数的振幅、偏移和移位?

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);

我的经验告诉我,尽可能少地依赖工具箱总是好的。对于您的特定情况,模型很简单,手动操作非常简单

假设您有以下模型:

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])
结果:

%// 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