我有一些不连续的数据,我想要一次分段拟合,因为有一个参数的拟合是共同的所有部分的函数。不连续点的数目和位置各不相同。
我考虑使用一个类并将不连续指标作为数据成员,然后使用具有不同数量输入的成员函数作为我发送给Matlab的fit函数的函数。
。
function f = approximate(obj,varargin)
f = zeros(size(varargin{1}));
for i = 1:nargin-3
x = varargin{1}(obj.segmentStartIdx(i):obj.segmentEndIdx(i));
f(obj.segmentStartIdx(i):obj.segmentEndIdx(i)) = varargin{2} + (0.25*(1-x/varargin{i+2}).^-2+x/varargin{i+2}-0.25);
end
end
显然,这不起作用…使用fit with
fittype = ('fp.approximate(x,A,B,C)');
Matlab抛出以下错误:
Error using fittype/testCustomModelEvaluation (line 12)
Expression fp.approximate(x,A,B,C) is not a valid MATLAB expression, has non-scalar coefficients, or cannot be evaluated:
Error in fittype expression ==> fp.approximate(x,A,B,C)
??? Attempt to reference field of non-structure array.
Error in fittype>iCreateFittype (line 371)
testCustomModelEvaluation( obj );
Error in fittype (line 328)
obj = iCreateFittype( obj, varargin{:} );
Error in fit>iFit (line 157)
model = fittype( fittypeobj, 'numindep', size( xdatain, 2 ) );
Error in fit (line 108)
[fitobj, goodness, output, convmsg] = iFit( xdatain, ydatain, fittypeobj, ...
Caused by:
Error using fittype/evaluate (line 102)
Error in fittype expression ==> fp.approximate(x,A,B,C)
??? Attempt to reference field of non-structure array.
尝试非成员函数没有解决问题,不确定我做错了什么,虽然…我将其简化为以下函数:
function [ f ] = moreArgTestFunc( p, xData )
f = zeros(size(xData));
global segmentStartIdx;
global segmentEndIdx;
for i = 1:length(p)-1
x = xData(segmentStartIdx(i): segmentEndIdx(i));
f(segmentStartIdx(i):segmentEndIdx(i)) = p(1) + (0.25*(1-x/p(i+1)).^-2+x/p(i+1)-0.25);
end
end
尝试在NonLinearModel中使用它。Fit或nlfit会导致以下错误:
Error using moreArgTestFunc (line 2)
Not enough input arguments.
所以我可能在这里遗漏了一些东西…
有更好的方法去做吗?
调用NonLinearModel。Fit、fitnlm或lsqcurvefit必须将函数的指针作为参数传递。我认为传递函数名称是足够的-但显然不是。使用匿名函数
funcToFit = @(p,x) myfunctionName(p,x)
然后传递funcToFit而不是myfunctionName作为参数解决了这个问题。
要拟合的参数数量的变化通过使用p的大小变化的向量来解决。