# fitting to a curve defined by an integral

25 views (last 30 days)
James Clarke on 8 Jul 2015
Edited: Jin Ow on 24 Apr 2020
Is it possible to use 'fit' to fit data to a function that involves an integral? Here's the code I'm using.
g = fittype('a*integral(@(tau) exp((-x-tau).*(a/b)),0,x)','coeff',{'a','b'});
fit(X,Y,g)
but this gives me the following error:
Error using fittype (line 356)
Expression a*integral(@(tau) (exp((-x-tau).*(a/b)),0,x) is not a valid MATLAB expression, has non-scalar
coefficients, or cannot be evaluated:
Error in fittype expression ==> a.*integral(@(tau) exp((-x-tau).*(a./b)),0,x)
??? A and B must be floating point scalars.
Does anybody know how to do this? Thanks in advance

#### 1 Comment

Jin Ow on 13 Apr 2020
Have you solved this problem?
I'm now fitting a curve defined by an integral as well, but error keeps coming out. T_T

Michael Soskind on 23 Apr 2020
Hi James and Jin,
Would you both be willing to take a bit of a different approach? The reason the fit is not working for you is that you are trying to input an array into the integral function. Instead of an array, I recommend making a function which can take an array in, and then using this to output an array of the integrated values. This is what I do in the code below:
% Defining coefficients for a sample plot
a = 10;
b = 12;
tau = 0.5;
% Creating the data to fit to
x = -1:0.1:1;
y = func(a,b,x,tau);
plot(x,y, 'x'); hold on; % plotting the data as points
% Implementing lsqcurvefit, which I prefer to fittype
coeff = lsqcurvefit(@(c, xdata) func(c(1), c(2), xdata, tau), [5,7], x, y);
plot(x,func(coeff(1), coeff(2), x, tau), '--') % plotting the fit as a dashed line
% defining the function that returns an array of the integrated values with an arry of input x values
function [y] = func(a, b, x, tau)
y = zeros(1, numel(x));
for i = 1:numel(x)
y(i) = a.*integral(@(x) exp((-x-tau).*(a./b)),0,x(i));
end
end Hopefully the above code can get you both on the right path towards successfully fitting your function.
Best,
Michael

#### 1 Comment

Jin Ow on 24 Apr 2020
thx. Actually I've solved this problem a week ago, and the method is similar as yours.
But still, thanks for providing a detailed example to this fitting problem. ;)