0

I am using nonlinearfit tool in matlab. I keep getting the following error:

Error using nlinfit (line 210) MODELFUN must be a function that returns a vector of fitted values the same size as Y (1-by-100). The model function you provided returned a result that was 1-by-2. One common reason for a size mismatch is using matrix operators (, /, ^) in your function instead of the corresponding element-wise operators (., ./, .^).

I found this question very similar to mine, but still I get the same error. I have tried calculating myfun on the console while using a vector as an input, which gives me output of correct dimension. It will be ton of help if anybody can point out the mistake.

% Defining the function
myfun = @(t,b)exp(t.*b(1)+b(2));
[y_a] = arrayfun(myfun,x_a);
% Using nonlinear least square minimization
beta0 = [1 1];
nlinfit(x,y,myfun, beta0)

Thanks in advance...:)

Edit: Found this to be working. g = fittype('exp(k*x + a)'); [fit1,gof,fitinfo] = fit(x',y',g,'StartPoint',[1 1]);

Community
  • 1
  • 1

1 Answers1

0

The function used in nlinfit takes the parameter vector as its first argument, then the independent data vector. You want,

myfun = @(b,t)exp(t.*b(1)+b(2));

Note that you could just use * rather than .* in this instance too.

Phil Goddard
  • 10,571
  • 1
  • 16
  • 28
  • What are your dimensions of `x` and `y`, and what error message do you get when the inputs to `myfun` correctly ordered? – Phil Goddard Jan 11 '16 at 06:45
  • Thank you for the comment, I have already tried it. I tried something like. `myfun = @(b,t)exp(t*b(1));` Even that simple function was giving me the same error. Also tried lsqcurvefit, got very much the same error. finally managed to get around it by using simple fit function. `g = fittype('exp(k*x + a)'); [fit1,gof,fitinfo] = fit(x',y',g,'StartPoint',[1 1]);` Not really sure what the problem was, but any insights will be cool! – swagat patnaik Jan 11 '16 at 06:47
  • The dimension of x = (1x100) and y = (1x100). I even tried transposing them into vectors, but didn't get any results. – swagat patnaik Jan 11 '16 at 06:49
  • Strange, as `x=1:100;y=x+randn(size(x));nlinfit(x,y,myfun,[0 0])` works fine. – Phil Goddard Jan 11 '16 at 17:12
  • Thanks for the comment: Tried changing it, but got the same msg **MODELFUN must be a function that returns a vector of fitted values the same size as Y (1-by-100). The model function you provided returned a result that was 1-by-2. One common reason for a size mismatch is using matrix operators (*, /, ^) in your function instead of the corresponding elementwise operators (.*, ./, .^).** I am not sure may some problem with the matlab version I have installed. – swagat patnaik Jan 12 '16 at 04:05