以下是如何以最小二乘的方式“手动”进行拟合:
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')