简体   繁体   English

在Matlab中拟合2D数据

[英]Fitting 2D data in Matlab

How would you fit a 2d curve such as ln(x^2) + 3y to an mxn array? 你如何将ld(x ^ 2)+ 3y等2d曲线拟合到mxn数组?

Update 更新

I mean I have mxn array and want fit it with a 2D curve. 我的意思是我有mxn数组,并希望它适合2D曲线。 Sorry for confusion. 抱歉混淆。

You can start with using meshgrid to generate two arrays that correspond to the indices of your mxn array (which we'll call z for simplicity). 您可以从使用meshgrid开始生成两个与mxn数组的索引相对应的数组(为简单起见,我们将其称为z)。 For example: 例如:

[x,y] = meshgrid(1:size(z,2),1:size(z,1));

Trace x and y in your command window to see their structure, it'll make sense. 在命令窗口中跟踪x和y以查看它们的结构,这是有意义的。

Then you can use a function such as lsqnonlin (nonlinear least squares) to fit a 2d curve to your matrix z. 然后,您可以使用lsqnonlin(非线性最小二乘)等函数将2d曲线拟合到矩阵z。 So if the curve you want to fit is "a log(x^2) + b y", where a and b are free parameters, then you could use something like this: 因此,如果您想要拟合的曲线是“ log(x ^ 2)+ b y”,其中a和b是自由参数,那么您可以使用以下内容:

%Define a function which returns the residual between your matrix and your fitted curve
myfun = @(params) params(1)*log(x(:).^2) + params(2)*y(:) - z(:)
%Define initial guesses for parameters a, b
params0 = [1,3];
%Add lots of debugging info
opts = optimset('Display','Iter');
%Fit
fitparams = lsqnonlin(myfun,params0,[],[],opts);

I would recommend running cftool . 我建议运行cftool It's actually quite capable for wizard-type gadget. 它实际上非常适合向导型小工具。

Here's a programmatic fitting example (I like the MATLAB documentation), and a perhaps pertinent excerpt: 这是一个程序化的拟合示例 (我喜欢MATLAB文档),以及一个可能相关的摘录:

s = fitoptions('Method','NonlinearLeastSquares',...
               'Lower',[0,0],...
               'Upper',[Inf,max(cdate)],...
               'Startpoint',[1 1]);
f = fittype('a*(x-b)^n','problem','n','options',s);

Fit the data using the fit options and a value of n = 2: 使用拟合选项和n = 2的值拟合数据:

[c2,gof2] = fit(cdate,pop,f,'problem',2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM