Minimize function with respect to multiple variables such that each variable has many variables?

8 次查看(过去 30 天)
I want to minimize a function with many variables
Suppose I have this function
function b = three_var(v,c)
p=length(v);
b = v(1)^2 + 2.5*sin(v(2)) -prod(v.*v)*c;
end
Then it is easy to do this
c=2;
fun=@(v)three_var(v,c);
v = [-0.6,-1.2,0.135, 1];
b_min = fminsearch(fun, v)
But suppose that the function is given by
function b = three_var(v,k,c)
p=length(v);
b = v(1)^2 + 2.5*sin(v(2)) +sum(k)-prod(v.*v)*c;
end
Where k is a vector. How can I find a way that minimizes my scalar b.
c=2;
fun=@(v,k)three_var(v,k,c);
v = [-0.6,-1.2,0.135, 1];
k=[3,2,1];
b_min = fminsearch(fun, v,k)
I am getting an obvious error because I am not using fminsearch in the right way but you know what i mean:
Error using fminsearch
Try Using Cell input
This did not work either, I tried rewriting the function as
function b = three_var(H,c)
v=H{1};
k=H{2};
p=length(v);
b = v(1)^2 + 2.5*sin(v(2)) +sum(k)-prod(v.*v)*c;
end
Then I wrote this
c=2;
H=cell(2,1);
H{1}=[-0.6,-1.2,0.135, 1];
H{2}=[3,2,1];
fun=@(v)three_var(v,c);
b_min = fminsearch(fun, H)
This gave me an error
Error using fminsearch (line 96)
FMINSEARCH accepts inputs only of data type double.
Can someone help me in this regards?

回答(1 个)

ABDULAZIZ ALTUN
ABDULAZIZ ALTUN 2020-3-11
The best way around it
I could not find a nice solution to this:
I wrote the following function
function b = three_var(Input,c,nv,nk)
v=Input(1:nv);
k=Input(nv+1:nv+nk);
p=length(v);
b = v(1)^2 + 2.5*sin(v(2)) +sum(k)-prod(v.*v)*c;
end
Where nv and nk are the length of each of the input vectors
c=2
v=[-0.6,-1.2,0.135, 1];
k=[3,2,1];
Input=[v,k];
nv=length(v);
nk=length(k);
fun=@(v)three_var(v,c,nv,nk);
b_min = fminsearch(fun, Input)
this have solved my problem but I am sure there is a better way of doing this.

类别

Help CenterFile Exchange 中查找有关 Get Started with Optimization Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by