1 view (last 30 days)

Show older comments

I need to optimize a function that only admits a scalar input. A simplified example could be:

function output = test(x)

a = [1,2,3];

element = x*a;

output = sum(element)

end

If i use fminbnd, matlab produces an error on the definition of element wich makes me suspect that the problem is that this definition doesn't work with x as vector.

Wich solution could I use in this case?

Just for reference, the real function I need to optimize is:

function diferencia = diferencia(sigma)

c0 = 343;

rho0 = 1.21;

f_m = linspace(120,2500,1e5);

Z0 = rho0*c0;

k0 = 2*pi*f_m/c0;

d_m = 25e-3;

X = rho0*f_m./sigma;

Zc = Z0*(1 + 0.057*X.^(-0.754) - 1j*0.087*X.^(-0.732));

k = k0.*(1 + 0.0978*X.^(-0.7) - 1j*0.189*X.^(-0.595));

Zs = -1j*Zc.*cot(k*d_m);

R = (Zs - Z0)./(Zs + Z0);

absor = 1 - abs(R).^2;

diferencia = abs(1 - absor);

end

Where optimizing with fminbnd. I obtain an error in the definition of X, wich envolves product of variable sigma with a vector.

John D'Errico
on 2 May 2021

Edited: John D'Errico
on 2 May 2021

FIRST, NEVER return a variable that has the same name as your function. That is a dangerously, recursively incestuous operation surely going to cause a problem.

function result = diferencia(sigma)

c0 = 343;

rho0 = 1.21;

f_m = linspace(120,2500,1e5);

Z0 = rho0*c0;

k0 = 2*pi*f_m/c0;

d_m = 25e-3;

X = rho0*f_m./sigma;

Zc = Z0*(1 + 0.057*X.^(-0.754) - 1j*0.087*X.^(-0.732));

k = k0.*(1 + 0.0978*X.^(-0.7) - 1j*0.189*X.^(-0.595));

Zs = -1j*Zc.*cot(k*d_m);

R = (Zs - Z0)./(Zs + Z0);

absor = 1 - abs(R).^2;

result = abs(1 - absor);

end

Next, what error did you get when you called fminbnd? IF YOU GET AN ERROR, TELL US WHAT THE ERROR WAS! Paste in the ENTIRE error response. everything in red.

Anyway, if I call your code, does it return a scalar when a scalar input is pased in ? NO! What is the requirement of codes lke fminbnd? READ THE HELP!

result = diferencia(2);

size(result)

ans =

1 100000

Is that a scalar value? It looks vaguely like a vector. Can fminbnd optimize a function that returns an entire vector? NO.

Your problem is not that you cannot optimize a function that takes only scalar input. It is that you apparently do not understand the purpose of an optimizer. An optimizer like fminbnd is designed to take a function that takes an input, and produces a SCALAR output. It finds the value of the input that minimizes the result.

I do note that in your test example, test DOES return a scalar value. But for some reason, you did not decide to do the same with the function diferencia. I don't even know what it means to minimize a vector.

So what is it about that vector of length 1e5 that you return that you wish to optimize?

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

Start Hunting!