How can one make this program work? (fmin question)

In Part 1, I have learned that
x_optimal = fminbnd(@fun,0,2)
function out=fun(x)
if x<=1 out=x; else out=sqrt(x); end
out=-out; %because we're maximizing
end
Now I want to parameterize this example. I want to define a parameterized function
function out=fun(x,a)
if x<=1 out=x; else out=a*sqrt(x); end
out=-out; %because we're maximizing
end
And want to create an output vector
x=zeros(10,1);
for a=1:1:10
x(a,1)=fminbnd(@fun,0,2) % minimizes fun(x,a)
end
But this code does not work. How can one make the code work?

 Respuesta aceptada

Bruno Luong
Bruno Luong el 2 de Ag. de 2020
x=zeros(10,1);
for a=1:1:10
x(a,1)=fminbnd(@(x) fun(x,a), 0, 2) % minimizes fun(x,a)
end

3 comentarios

alpedhuez
alpedhuez el 2 de Ag. de 2020
Editada: alpedhuez el 2 de Ag. de 2020
Thank you.
  1. How did you arrive at this solution?
  2. I thought of using a global variable. Which is better?
global a
x=zeros(2,1);
for n=1:1:2
a=n;
x_optimal(n,1) = fminbnd(@fun,0,2)
end
function out=fun(x)
global a
if x<=1 out=1; else out=a*sqrt(x); end
out=-out; %because we're maximizing
end
Bruno Luong
Bruno Luong el 2 de Ag. de 2020
" How did you arrive at this solution? "
Strictly speaking I did not arrive at this solution, since I did not search for it.
I simply kwow MATLAB and anonymous function by mainly reading the doc and then practice.
Don't use global variable if you don't have to.
alpedhuez
alpedhuez el 2 de Ag. de 2020
Okay.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Construct and Work with Object Arrays en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 2 de Ag. de 2020

Comentada:

el 2 de Ag. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by