Set function workspace based on MATLAB

I have a rather cumbersome program that I ran as a script from the MATLAB command line. I decided to clean some nested functions a bit (I need to store everything in one file), but for this I also needed to make the program the function itself. As a result, the program no longer works in the base workspace, as was the case with the script. This means that I no longer have access to dozens of useful variables that remained after the program was launched, which is important for additional calculations and startup information.

Suggested workarounds that I can find - to use it assignin, evalinto define variables as global or set out in the definition of the current functionality of the program. However, none of these solutions appealed to me, and I really would like to find a way to make the workspace build on my own. Is there such a workaround? Or is there another way to do this that does not require me to manually define or label each specific variable that I want to get from a function?

+4
source share
2 answers

. - . , , , , , .

, , .

, , whos, assignin eval:

function your_function()
   x = 'hello' ;
   y = 'world' ;

   variables = whos ;
   for k=1:length(variables)
      assignin('base',variables(k).name,eval(variables(k).name))
   end
end

, . , :

function out = your_function()
   x = 'hello' ;
   y = 'world' ;

   out.x = x ;
   out.y = y ;
 end
+2

, , , .

- , , struct, struct .

function AllVariables = GlobalFunction(varargin);
% bunch of stuff

AllVariables= struct('Variable1', Variable1, 'Variable2', Variable2, …);
end
0

All Articles