[英]Fit Arbitrary Curve to Data Points in Matlab
我想将y = a + b * sin(2 * pi * x)+ c * cos(2 * pi * x)形式的曲线拟合到Matlab中的某些数据点。 我一直在尝试使用'fit',但随后我仅收到此消息'if isa(fittypeobj,'fittype')'
这是我的代码:
L = load('file.mat');
x = filedata(:,1);
ft = fittype('a+b*sin(2*pi*x)+c*cos(2*pi*x)');
fit(x, filedata(:,3), ft)
有人可以告诉我我在做什么错吗?
这是如何以最小二乘法“手动”进行拟合:
x = x(:); %make sure we have column vectors
y = y(:);
f0 = 1;
M = [ones(size(x)), sin(2*pi*f0*x), cos(2*pi*f0*x)];
%design matrix, columns are base vectors
% least square approximation of x = k(1)*M(:,1) + k(2)*M(:,2) + k(3)*M(:,3);
% see help mldivide
k = M \ y;
a = k(1);
b = k(2);
c = k(3);
快速测试以查看是否有效:
>> x = linspace(0,10,1000)'; % note transpose to make column
>> y = 3 + 1.5 * sin(2*pi*x) + 8 * cos(2*pi*x) + randn(size(x)); % add some noise
>> f0 = 1;
>> M = [ones(size(x)), sin(2*pi*f0*x), cos(2*pi*f0*x)];
>> k = M \ y
k =
3.0383
1.5264
7.9385
>> plot(x, y, x, M*k, 'r'); legend('measurement', 'fit')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.