Passing variable from anonymous objective function to main workspace

3 ビュー (過去 30 日間)
Mario Malic
Mario Malic 2020 年 7 月 28 日
コメント済み: Mario Malic 2020 年 11 月 2 日
Hello guys, I have a quick and simple question for you about passing variables from anonymous objective functions.
[x, fval] = fmincon(@(x)objfun(x,var1, var2),x0)
And in this objfun I am calculating and saving some information in variable data (cell). After optimization is done, I would like to have that variable into my workspace. Currently I am declaring it as a global variable and of course since it's bad practice. Is there an alternative way to do it?
Saving into variable data for each iteration seems a little bit tedious.
  1 件のコメント
Mario Malic
Mario Malic 2020 年 11 月 2 日
+1 on both answers since they both solve the problem. It takes a bit of time for me to understand nested functions, especially the way they are written. I went for Stephen's answer, just because of simplicity.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2020 年 7 月 29 日
編集済み: Stephen23 2020 年 7 月 29 日
You can do this easily with nargin:
function val = objfun(x,v1,v2)
persistent data
if ~nargin
val = data;
return
end
... your code
end
and then call it after the fmincon call:
data = objfun();

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2020 年 7 月 28 日
Mario - consider nesting your optimization function within the main function and have it return the variable to the workspace. See Nested Functions for details. An example of this might be
function [data] = myMainFunction
data = [];
function myNestedFunction(x)
% do something
for k = 1:ceil(x)
data(k) = k;
end
end
% call the nested function
myNestedFunction(42);
end
The above code would be saved to a file named myMainFunction.m. It would be called from the command line as
>> x = myMainFunction;
  1 件のコメント
Mario Malic
Mario Malic 2020 年 7 月 28 日
Thanks Geoff, I'll try and report tomorrow.

サインインしてコメントする。

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by