MATLAB: How to correct ”Function definitions are not permitted in this context.”

function definitions

I am trying to solve an optimization problem with multi objective genetic algorithms and I am having this error even I stored the file as (multiobj.m). Thanks in advance.
clear all
clc
%%given
D=0.1;
W=10e3;
ns=40;
x(3)=0.005;
x(1)=100e-6;
x(2)=0.4;
row=860;
Cp=4.19*10^3;
%%the average Reynolds number
U=pi*D*ns;
Re=(row*x(1)*U)/x(3);
%%the correction coefficients
if (Re<510)
alpha=1;
G=1/12;
elseif (510<=Re<1125)
alpha=5.914*Re^(-0.285);
G=2.915*Re^(-0.57);
elseif (1125<=Re<13500)
alpha=0.798;
G=2.915*Re^(-0.57);
else
alpha=0.756;
G=14.45*Re^(-0.75);
end
%%modified Sommerfield number
S=(ns*x(3)*(D^3)*x(2))/(48*G*(x(1)^2)*W);
%%the eccentricity ratio
epsilon=exp(-2.236*alpha*x(2)*sqrt(S));
%%the maximum film pressure
theta=1/(cos((1-sqrt(1+24*epsilon^(2)))/(4*epsilon)));
Pmax=((pi*ns*x(3)*D^(2)*alpha^(2)*x(2)^(2))/(8*G*x(1)^(2)))*((epsilon*sin(theta))/((1+epsilon*cos(theta))^(3)));
%%the friction force on the journal surface
if (Re<1125)
Fj=((pi^(2)*x(3)*ns*D^(3)*x(2))/(48*G*x(1)))*((1/sqrt(1-epsilon))+((1-epsilon)/(1-epsilon^(2))^(3/2)));
elseif (1125<=Re<13500)
Fj=((pi^(2)*x(3)*ns*D^(3)*x(2))/(48*G*x(1)))*((1.109*epsilon^(2))-(1.49*epsilon)+2.748);
else Fj=((pi^(2)*x(3)*ns*D^(3)*x(2))/(48*G*x(1)))*((1.792*epsilon^(3))-(1.523*epsilon^(2))-(3.697*epsilon)+8.734);
end
lb=[40e-6;0.2;0.0001];
ub=[300e-6;0.6;0.001];
A=[-1 0 0;1 0 0;0 -1 0;0 1 0;0 0 -1;0 0 1];
b=[-40e-6;300e-6;-0.2;0.6;-0.0001;0.001];
nvars=3;
function f=multiobj(x)
f(1)=(pi/4)*ns*x(1)*D^(2)*epsilon;
f(2)=(2*Fj)/(row*Cp*D*x(1)*epsilon);
end
[x,f,exitflag,output]=gamultiobj(@multiobj,nvars,A,b,[],[],lb,ub)

Best Answer

You can copy the complete code to a function:
[EDITED] Parameters added to multiobj():
function [x,f,exitflag,output] = yourFcn
% clear all % Omit this waste of time
clc
%%given
D=0.1;
... % Left out due to clarity
nvars=3;
fcn = @(x) multiobj(x, ns, D, epsilon, row, CP, Fj);
[x, f, exitflag, output] = gamultiobj(fcn,nvars,A,b,[],[],lb,ub)
end
function f = multiobj(x, ns, D, epsilon, row, CP, Fj)
f(1) = (pi/4) * ns * x(1)* D^(2) * epsilon;
f(2) = (2*Fj) / (row * Cp * D * x(1) * epsilon);
end
In modern Matlab versions functions can be defined in scripts also, but not in the middle of it. But using functions is much better, because it keeps the workspace clear and you can omit the darn clear all.