MATLAB: Globalsearch not working for a function file.

MATLAB: Globalsearch not working for a function file.


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;
for n=1:N;
a(n)= ((n-1)*(amax-amin))/(N-1)+amin;
c(n)= a(n)./b(n);
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));
My solver is below to call the function file…
opts = optimoptions(@fmincon,'Algorithm','interior-point');
problem = createOptimProblem('fmincon','x0',randn(2,1),...
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 1×1. 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 1×49000 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.
  • Add a Comment

    Your email address will not be published. Required fields are marked *