MATLAB Answers

Nonlinear least-squares data fit

5 views (last 30 days)
I am trying to make a data fit for the data attached to this post,Nu=f(Re,Theta,Beta).I use lsqnonlin(fun,x0) function for this purpose.I have created a script file for this fitting,but everytime I try to run the script,the program always shows error messages.So,what is the problem with this script.
clc
clear all
% Create an anonymous function that describes the expected relationship
% between X and Y
f=@(c,x) c(1).*(x(:,1).^c(2)).*(x(:,2).^c(3)).*(x(:,3).^c(4))./x(:,4)-1;
% data set
% Specify x variables from data file,Re,Theta and Beta columns.
x=xlsread('all data for fitting');
% Specify y variable from data file ,(Nu)column.
y=x(:,4);
% Specify a vector of starting conditions for the solvers
c0=[1;1;1;1];
% Perform a nonlinear regression
c=lsqnonlin(f,c0);

  0 Comments

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 14 Aug 2020
The objective function needs to be coded as:
ffcn = @(c) f(c,x) - y;
with the complete lsqnonlin call being:
f=@(c,x) c(1).*(x(:,1).^c(2)).*(x(:,2).^c(3)).*(x(:,3).^c(4))./x(:,4)-1;
ffcn = @(c) f(c,x) - y;
c0=[1;1;1;1];
C = lsqnonlin(ffcn, c0);
producing:
C =
1.0308e-01
1.3246e+00
1.9801e-06
-4.6017e-01
.

  13 Comments

Star Strider
Star Strider on 18 Aug 2020
I have no idea what is throwing that error. The code appears to be correct, however my code runs correctly on R2020a, so be certain the code is correct for R2013a. There have been many changes in the last 7 years, and I no longer have access to the documentation for R2013a.
MOHAMED ABDULAZIM
MOHAMED ABDULAZIM on 19 Aug 2020
Did you try to run this script on your version?
Star Strider
Star Strider on 19 Aug 2020
I used this:
D = xlsread('all data for fitting.xlsx');
x = D;
y = x(:,4);
f=@(c,x) c(1).*(x(:,1).^c(2)).*(x(:,2).^c(3)).*(x(:,3).^c(4));
ffcn = @(c) (f(c,x) - y)./y;
ftns = @(c) norm(ffcn(c));
PopSz = 500;
Parms = 4;
opts = optimoptions('ga', 'PopulationSize',PopSz, 'InitialPopulationMatrix',randi(1E+4,PopSz,Parms)*1E-4, 'MaxGenerations',2E3, 'PlotFcn',@gaplotbestf, 'PlotInterval',1);
t0 = clock;
fprintf('\nStart Time: %4d-%02d-%02d %02d:%02d:%07.4f\n', t0)
[theta,fval,exitflag,output] = ga(ftns, Parms, [],[],[],[],-Inf(Parms,1),Inf(Parms,1),[],[],opts)
t1 = clock;
fprintf('\nStop Time: %4d-%02d-%02d %02d:%02d:%07.4f\n', t1)
GA_Time = etime(t1,t0)
QQQ1 = datetime([zeros(1,5) GA_Time], 'Format','HH:mm:ss.SSS')
fprintf('\nElapsed Time: %23.15E s ', GA_Time)
fprintf(1,'\tRate Constants:\n')
for k1 = 1:length(theta)
fprintf(1, '\t\tTheta(%d) = %12.5E\n', k1, theta(k1))
end
and when I ran that just now, got these parameter estimates:
theta =
2.8517e+000 431.7000e-003 99.6000e-003 -324.6437e-003
with a fitness value of:
fval =
5.5386e+000
.

Sign in to comment.

More Answers (0)

Products


Release

R2013a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!