在Matlab中将任意曲线拟合到数据点 [英] Fit Arbitrary Curve to Data Points in Matlab

查看:882
本文介绍了在Matlab中将任意曲线拟合到数据点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将y = a + b * sin(2 * pi * x)+ c * cos(2 * pi * x)形式的曲线拟合到Matlab中的某些数据点.我一直在尝试使用'fit',但是我只会收到此消息'if isa(fittypeobj,'fittype')'

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

这是我的代码:

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?

推荐答案

以下是如何以最小二乘法手动"进行拟合的方法:

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

这篇关于在Matlab中将任意曲线拟合到数据点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆