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]);

1 Answer 1

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.

5
  • What are your dimensions of x and y, and what error message do you get when the inputs to myfun correctly ordered? Commented Jan 11, 2016 at 6: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! Commented Jan 11, 2016 at 6:47
  • The dimension of x = (1x100) and y = (1x100). I even tried transposing them into vectors, but didn't get any results. Commented Jan 11, 2016 at 6:49
  • Strange, as x=1:100;y=x+randn(size(x));nlinfit(x,y,myfun,[0 0]) works fine. Commented Jan 11, 2016 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. Commented Jan 12, 2016 at 4:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.