0

我想将 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)

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

4

1 回答 1

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')
于 2013-08-26T08:26:50.800 回答