Passing variable from anonymous objective function to main workspace
Show older comments
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 Comment
Mario Malic
on 2 Nov 2020
Accepted Answer
More Answers (1)
Geoff Hayes
on 28 Jul 2020
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 Comment
Mario Malic
on 28 Jul 2020
Categories
Find more on Surrogate Optimization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!