Create function handle with several variables/arguments
조회 수: 20 (최근 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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!