Asked by Manuel
on 11 Feb 2013

is it possible to fit the parameters of a non linear model with more than 2 independent variable (let's say 3 or 4 for example) to data???

here attached is my code, where the coefficients are a b c d and the independent variables are x,q,w

function [beta]=fitgen(Xtest,Ytest,Wtest,Ztest,p,p_low,p_up)

mdl=@(a,b,c,d,w,q,x) zfit(a,b,c,d,w,q,x);

algo1='Trust-Region';

fit_opt = fitoptions('Method','NonlinearLeastSquares',... 'Lower',p_low,'Upper',p_up,... 'Robust','on',... 'Normalize','off',... 'Algorithm',algo1); fit_typ = fittype(mdl,'option',fit_opt);

[Yfitt,gof,output]=fit([Xtest,Ytest,Wtest],Ztest,fit_typ,'Start',p)

%%where the function zfit is (I used a linear model just for sake of simplicity, but the final purpose is to fit a non linear model):

function [z]=zfit(a,b,c,d,w,q,x)

[x,q,w]=meshgrid(x,q,w);

z=a*x+b*q+c*w+d;

end

thank you very much in advance

Answer by the cyclist
on 11 Feb 2013

Accepted answer

Yes, if you have the Statistics Toolbox you can use the nlinfit() function to do this. Here is a very simple example.

function [] = nlinfitExample()

% Here is an example of using nlinfit(). For simplicity, none of % of the fitted parameters are actually nonlinear!

% Define the data to be fit x=(0:1:10)'; % Explanatory variable y = 5 + 3*x + 7*x.^2; % Response variable (if response were perfect) y = y + 2*randn((size(x)));% Add some noise to response variable

% Define function that will be used to fit data % (F is a vector of fitting parameters) f = @(F,x) F(1) + F(2).*x + F(3).*x.^2; F_fitted = nlinfit(x,y,f,[1 1 1]);

% Display fitted coefficients disp(['F = ',num2str(F_fitted)])

% Plot the data and fit figure plot(x,y,'*',x,f(F_fitted,x),'g'); legend('data','fit')

end

In my case, I just have one explanatory variable vector, x, but that could have been a matrix with multiple variables in each column.

Hope that helps.

Answer by Manuel
on 11 Feb 2013

Thank you very much it works.

Does anyone knows how to apply boundary condition to the parameters during the fitting using the function nlinfit?

Thank you a lot

the cyclist
on 11 Feb 2013

Opportunities for recent engineering grads.

## 0 Comments