MATLAB: Globalsearch not working for a function file.

equationglobalsearch

Hello, Globalsearch is not able to solve my equation in function file. It is giving me an error -'Supplied objective function must return a scalar value'.I would really appreciate your help. My function file is…
function F = Trans_eqn_taperedfiber(beta)
m = 0;
lambda = 1550*10^-3;
n1 = 1.45;
n2 = 1.43;
n3 = 1;
k0 = 2*pi/lambda;
N = 49000;
a=zeros(0,N);
b=zeros(0,N);
c=zeros(0,N);
amax=52.5;
amin=40*10^-3;
bmax=62.5;
bmin=0;
for n=1:N;
a(n)= ((n-1)*(amax-amin))/(N-1)+amin;
b(n)=((n-1)*(bmax-bmin))/(N-1)+bmin;
c(n)= a(n)./b(n);
end
F = [(besselj(m,a.*sqrt(n1^2*k0^2-beta(1).^2))-bessely(m,(a.*sqrt(n1^2*k0^2-beta(1).^2).*c))).*(besselk(m,b.*sqrt( -n3^2*k0^2 + beta(2).^2))-besselj(m,b.*sqrt(n2^2*k0^2- beta(1).^2)))./(besselj(m,a.*sqrt(n1^2*k0^2-beta(1).^2))-besselj(m,b.*sqrt(n2^2*k0^2- beta(1).^2).*c)).*(besselk(m,b.*sqrt( -n3^2*k0^2 + beta(2).^2))-bessely(m,(b.*sqrt(n2^2*k0^2- beta(1).^2)).*c));
(besselj(m,(b.*sqrt(n2^2*k0^2- beta(1).^2)).*c).*bessely(m+1,b.*sqrt(n2^2*k0^2- beta(1).^2)))./(besselj(m+1,b.*sqrt(n2^2*k0^2- beta(1).^2)).*bessely(m+1,(b.*sqrt(n2^2*k0^2- beta(1).^2)).*c))];
F = sqrt(dot(F,F));
end
My solver is below to call the function file…
opts = optimoptions(@fmincon,'Algorithm','interior-point');
problem = createOptimProblem('fmincon','x0',randn(2,1),...
'objective',@Trans_eqn_taperedfiber,'lb',[5,7.5],'ub',[5,7.5],...
'options',opts);
gs = GlobalSearch;
[beta] = run(gs,problem);
Thanks in advance, Chetna.

Best Answer

Lets start by reading the error message: "Supplied objective function must return a scalar value"
So, the objective function must return a scalar value. A scalr has size 1x1. Lets run the objective function and see if it returns a scalar value:
>> X = Trans_eqn_taperedfiber([1/3,2/3]);
>> size(X)
ans =
1 49000
Is 1x49000 scalar? No. So the problem is your function returns a vector, which both the documentation and the error message clearly state is not allowed. You need to change your function to return a scalar value. Also note that you could generate a, b, and c without the loop using simpler vectorized code.
Related Question