Non-linear fitting for more than three variables
29 views (last 30 days)
I have a heat transfer experimental data set whrere Nu=f(Re,Theta,Beta).The data file is attached to this question.I want to make a non-linear curve fitting for this data set, so I wrote the following script file.For clarification purpose,Firstly,I imported the data from excel sheet as a matrix named data and as column vectors in the second import,each column is named according to the name in the excel sheet.When I try to run the script ,many errors prevent the running.Is this script correct for running?
% Create an anonymous function that describes the expected relationship
% between X and Y
% data set
% Specify x variables from data file,Re,Theta and Beta columns.
% Specify y variable from data file ,(Nu)column.
% Specify a vector of starting conditions for the solvers
% Perform a nonlinear regression
Alan Stevens on 13 Aug 2020
Edited: Alan Stevens on 14 Aug 2020
Because of the form of the desired fit, one can also do a fit by first taking logs. See the coding and result below. (Note Theta is turned into radians and 2pi added in order to avoid having zero angles give problems when taking logs). I've assumed the data is in the workspace with the names Nu, Re, Theta and Beta:
% Logarithmic variables
nu = log(Nu);
re = log(Re);
theta = log(Theta); %% Theta here is Theta*180/pi + 2pi to convert to radians and remove zeros.
beta = log(Beta);
% Construct vector and matrix
n = length(nu);
V = [sum(nu); sum(nu.*re); sum(nu.*theta); sum(nu.*beta)];
M = [n sum(re) sum(theta) sum(beta);
sum(re) sum(re.^2) sum(re.*theta) sum(re.*beta);
sum(theta) sum(theta.*re) sum(theta.^2) sum(theta.*beta);
sum(beta) sum(beta.*re) sum(beta.*theta) sum(beta.^2)];
c = M\V;
c1 = exp(c(1));
nufit = @(re,theta,beta) c(1) + c(2)*re + c(3)*theta + c(4)*beta;
Nufit = @(Re,Theta,Beta) c1*(Re.^c(2)).*(Theta.^c(3)).*(Beta.^c(4));
nuvals = nufit(re,theta,beta);
legend('log target','log fit')
Nuvals = Nufit(Re,Theta,Beta);
Here is the final comparison graph:
Just out of interest I've calculated the Pearson correlation coefficient for this fit:
Matt J on 13 Aug 2020
Edited: Matt J on 13 Aug 2020
When I try to run the script ,many errors prevent the running.Is this script correct for running?
No, you need to be using .* to do your vectorized multiplications. Also, you have many rows where x(:,2)=0 which cannot possibly agree with your model, and causes all kinds of NaNs to be generated during the iterative search.
Also, are the coefficients all supposed to be non-negative? If so, nlinfit will not let you apply positivity constraints. I would recommend lsqcurvefit instead,
c0=[e,X]\Y; c0(1)=exp(c0(1)); %Use log-linearity of the model
I assume Alex did something similar, since the result I get from this is very close to his,
0.6438 0.7292 -0.2038 -0.4317
0.2564 0.7363 0.0000 -0.4029