Fit Arbitrary Curve to Data Points in Matlab

爷,独闯天下 提交于 2019-12-12 06:24:16

问题


I would like to fit a curve on the form y=a+b*sin(2*pi*x)+c*cos(2*pi*x) to some data points in Matlab. I've been trying to use 'fit' but then I only get this message 'if isa( fittypeobj, 'fittype' )'

This is my code:

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)

Can somebody please tell me what I'm doing wrong?


回答1:


Here is how to do the fit 'by hand' in a least-squares way:

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

Quick test to see if it works:

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


来源:https://stackoverflow.com/questions/18433455/fit-arbitrary-curve-to-data-points-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!