How can I convert a function with multivariable input to a function with single vector input?

조회 수: 2 (최근 30일)
Hi, I want to use fmincon, and fmincon can deal with only function with single vector input.
When my formula is as below, it works well.
fun = @(x) x(1)^2+x(2)^2;
fmincon(fun,[1,1])
However, if the function form has multiple input as below, it does not work.
Is there any way to convert the fun2 below to the function with single vector input as the example above?
fun2 = @(x,y) x^2+y^2;
fmincon(fun2,[1,1]) % this does not work

답변 (1개)

Star Strider
Star Strider 2022년 3월 31일
Do essentially the same thing, creating it with another anonymous function around it —
fun2 = @(x,y) x^2+y^2;
fmincon(@(b)fun2(b(1),b(2)),[1,1]) % now it works!
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
ans = 1×2
0 0
.
  댓글 수: 2
Junho Kweon
Junho Kweon 2022년 3월 31일
Thank you so much @Star Strider!!
Is there any generalized way for this for the case of there are n-number of input element without typing b(1), b(2),....b(n)?
Star Strider
Star Strider 2022년 3월 31일
My pleasure!
I am not aware of any. The ‘shell’ anonymous function would have to be writen specifically for each funciton.
For example, if the function needed to have extra parameters passed to it:
fun2 = @(x,y,a,b) a*x^2+b*y^2;
a = 3;
b = 11;
fmincon(@(b)norm(fun2(b(1),b(2),a,b)),[1,1]) % now it works!
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
ans = 1×2
1.0e-03 * 0.0019 -0.2844
There could not possibly be a general rule that would apply to all functions.
.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by