How to save a variable from an anonymous function?
古いコメントを表示
I am using the function fmincon to minimize the function f:
[X,f]=fmincon(@(X) obj_function(X,P,Pd,intervalotiempo),X0,A,B,Aeq,Beq,LB,UB,@(X)nonlcon(X,Potnominal,intervalotiempo,Pd));
fmincon requires the use of anonymous funtions, therefore the variables that are used in nonlcon are not stored after runing the program.
I would like to know if it is possible to save (get it as an output) one varible from the function nonlcon.
採用された回答
その他の回答 (1 件)
Stephan
2019 年 7 月 19 日
1 投票
for nonlcon it's not necessarily an anonymous function that is needed. you can also use a "normal" function, so that you can save the needed values or display them.
3 件のコメント
Maria Sanz
2019 年 7 月 23 日
編集済み: Maria Sanz
2019 年 7 月 23 日
Walter Roberson
2019 年 9 月 20 日
function driver
various things here
Potnominal = value;
intervalotiempo = value;
Pd = value;
stored_intermediate_results = {};
[x, fval] = fmincon(@objective_function, A, b, Aeq, beq, lb, ub, @nonlcon, options);
save('AppropriateName.mat', 'x', 'fval', 'stored_intermediate_results');
function [c, ceq] = nonlcon(X)
%here Potnominal, intervalotiempo, Pd, stored_intermediate_results are all shared variables
temp1 = some expression in X and Potnominal and intervalotiempo and Pd
temp2 = some expression in X and Potnominal and intervalotiempo and Pd
c = some expression in X and Potnominal and intervalotiempo and Pd and temp1 and temp2
ceq = some expression in X and Potnominal and intervalotiempo and Pd and temp1 and temp2
stored_intermediate_results(end+1) = {X, temp1, temp2};
end
end
No anonymous function. But it would not have mattered, because you could instead use
function driver
various things here
Potnominal = value;
intervalotiempo = value;
Pd = value;
stored_intermediate_results = {};
[x, fval] = fmincon(@objective_function, A, b, Aeq, beq, lb, ub, @(X)nonlcon(X,Potnominal,intervalotiempo,Pd), options);
save('AppropriateName.mat', 'x', 'fval', 'stored_intermediate_results');
function [c, ceq] = nonlcon(X,Potnominal,intervalotiempo,Pd)
%here Potnominal, intervalotiempo, Pd are all parameters
%here stored_intermediate_results is a shared variable
temp1 = some expression in X and Potnominal and intervalotiempo and Pd
temp2 = some expression in X and Potnominal and intervalotiempo and Pd
c = some expression in X and Potnominal and intervalotiempo and Pd and temp1 and temp2
ceq = some expression in X and Potnominal and intervalotiempo and Pd and temp1 and temp2
stored_intermediate_results(end+1) = {X, temp1, temp2};
end
end
There is a small execution time difference between these two, with the parameter version being slightly faster than the shared variable version.
カテゴリ
ヘルプ センター および File Exchange で Solver Outputs and Iterative Display についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!