Create function handle with several variables/arguments
73 ビュー (過去 30 日間)
古いコメントを表示
Hello,
for my master thesis I want to minimize functions of multiple (50+) variables. So far I am doing this by using the function handle commands for an anonymous function. But since I would like to automatically set the right number of terms depending on the current problem, I am wondering, if there is not a better way to do this. What I am doing right now is something like this:
fun = @(z) cv(1)*z(1)+cv(2)*z(2)+cv(3)*z(3)+cv(4)*z(4)+cv(5)*z(5)+cv(6)*z(6)+cv(7)*z(7)+cv(8)*z(8)+...
options = optimoptions(@fmincon,'Display','notify-detailed','Algorithm',algorithm_outside,'MaxFunEvals',50000); %,'ConstraintTolerance',1e6);
startwert = initiations(l,:);
%startwert = Solution(:,3)';
%[mini,min_value] = fmincon(fun,startwert,Aeqb,constraints3,Aeqa,beq,zeros(1,number_of_links),ones(1,number_of_links)*total_demand,[],options);
problem = createOptimProblem('fmincon','objective',fun,'x0',startwert,'Aineq',Aeqb,'bineq',constraints3,'Aeq',Aeqa,'beq',beq,'lb',zeros(1,number_of_links),'ub',ones(1,number_of_links)*total_demand,'options',options);
gs = GlobalSearch;
[mini,min_value] = run(gs,problem);
Obviously, the cv(k) are just some values of type double, that have been calculated before. The same is true for the starting value and the constraints. The variables of the objective fucntion represent links in a traffic network. I would like to be able to tell my script in the beginning that my network has, say n links, and then to automatically have a function handle of the above type with the correct number of variables. What I am doing so far, is that I manually type the number of variables needed, what would amount in an awful lot of work for large networks, potentially in danger of typing mistakes.
Am I right, that this is not working that easily with, for example, a loop?
Thanks in advance for your help!
Regards, David
0 件のコメント
採用された回答
Stephen23
2019 年 2 月 12 日
編集済み: Stephen23
2019 年 2 月 12 日
Why not just vectorize the multiplication and summation?:
fun = @(z) sum(cv(:).*z(:));
2 件のコメント
Akshay Yadav
2020 年 10 月 21 日
Are all the variables z(1), z(2), ..., different? I am trying to make a similar function with 50 temperature variables:
for m = 1:50
f = @(T) sum(A(m,:).*T(:));
dTdt(m,1) = {f};
end
Where A is a 50x50 coefficient matrix. However, I am only able to evaluate dTdt at only one temperature.
>> dTdt{45,1}(1)
ans =
0.0012
If try to input multiple variables, it gives the error (like dTdt{45,1}(1,2,1,2,...)) :
Error using Part_2>@(T)sum(A(m,:).*T(:))
Too many input arguments.
Is it possible to evaluate each dTdt at different T(1), T(2), ..., T(50)?
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!