Hi. I'm using matlab on my research at the university and an optimization protocol which is fmincon function. Although I make the formula like, y =@(x)(x(1)+1)^2 + (x(2)+5)^2, as my research progresses, the formula will be much longer and complex. So I'd like to dismantle this function like y1=@(x)(x(1)+1)^2 + (x(2)+5)^2; y2=@(x)(x(3)+21)^2 + (x(4)+10)^2; after that , connect them like y = y1 + y2;
I tried this, but failed. Do you know how to deal with it?

 Respuesta aceptada

Star Strider
Star Strider el 14 de Dic. de 2017
Do you know how to deal with it?
Create another anonymous function that calls the other functions.
If you have one ‘x’ vector, this will work:
y = @(x) y1(x) + y2(x);
Example —
x = [3 5 7 11];
Out = y(x)
TestV = [(x(1)+1).^2 (x(2)+5).^2 (x(3)+21).^2 (x(4)+10).^2]
SumV = sum(TestV)
yields:
Out =
1341
TestV =
16 100 784 441
SumV =
1341

5 comentarios

Thank you for your early answer. And it worked!
I've thought about it for a long time, so your answer is very helpfull.
And if you don't mind,I want you to answer one more question. I want to optimize this formula with one condition.
y=@(x)(x(1)+1).^2 + (a*x(2)+5).^2
s.t a = 1 (x(2)>10), a = -1 (x(2)<=10)
Can we solve this problem using fmincon or other protocol provided by matlab?
y=@(x)(x(1)+1).^2 + (((x(2)>10)*2-1) * x(2) + 5).^2;
fminsearch(y,[rand,rand])
Star Strider
Star Strider el 14 de Dic. de 2017
The fmincon and other constrained optimization functions set conditional limits on the variables but not on other parameters.
The only way I can see to do that is to hard-code it as:
y=@(x) (x(1)+1).^2 + ([(1*(x(2)>10)) + (-1*(x(2)<=10))].*x(2)+5).^2'
x0 = ...;
x = fminsearch(y, x0)
then optimise ‘x’. (I use fminsearch here, other nonconstrained functions will also work.)
Kazuma Yamashita
Kazuma Yamashita el 14 de Dic. de 2017
Thank you, both of you! I could make it!
Star Strider
Star Strider el 14 de Dic. de 2017
Our pleasure.
Also, the discontinuity will cause problems for gradient-descent optimizers. The derivative does not exist as the discontinuity. Since fminsearch does not use that, it will work.
If my Answer helped you solve your problem, please Accept it!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre 関数の基礎 en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 14 de Dic. de 2017

Comentada:

el 14 de Dic. de 2017

Community Treasure Hunt

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

Start Hunting!