在Matlab中拟合任意曲线到数据点

时间:2013-08-25 20:38:21

标签: matlab curve-fitting

我想在形式上拟合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)

有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

以下是如何以最小二乘方式“手动”进行拟合:

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