About summing of anonymous function

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?

 采纳的回答

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 个评论

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])
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.)
Thank you, both of you! I could make it!
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!

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 関数の基礎 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!