1

For the sake of simplicity I am using MATLAB scripts as configuration files in my application. This way I can use the function run to load all variables into the workspace. Currently I am writing the code below out each and every time I need to load a configuration file.

configFile = [APP.PROJECT_DIR '/config/app.m'];
    if exist(configFile, 'file') ~= 2
        error('Missing configuration file for APP: [PROJECT ROOT DIR]/configFile/app.m')
    end
    run(configFile);

To reduce the amount of lines, I would like to place the above code in a standalone function. However if I do that the variables from the configuration file are loaded in that function instead of into the calling function. How could I manage to expose the workspace of a called function to the workspace of the calling function?

Basically what I want is the functionality of run + a check for file existince + custom error message if file does not exist.

Aeronaelius
  • 1,291
  • 3
  • 12
  • 31

2 Answers2

2

Some possible (mutually exclusive) approaches:

  • Make the function return those variables as outputs.
  • Declare those variables as global.
  • Use a script instead of a function. That would probably be my choice.
  • If none of the above suits your needs, you can use evalin. Not good practice, though.
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Globals are right up there in terms of [not](http://stackoverflow.com/questions/7888899/global-could-be-very-inefficient) [good](http://www.mathworks.com/matlabcentral/answers/51946-systematic-do-not-use-global-don-t-use-eval) [practice](http://blogs.mathworks.com/videos/2010/03/08/top-10-matlab-code-practices-that-make-me-cry/) except in very specialized cases, just like `eval`. This might be one of those cases. Another option is to re-write all code as a class using [OOP](http://www.mathworks.com/help/matlab/object-oriented-programming.html). – horchler Sep 01 '14 at 15:13
  • @horchler Thanks for the links. I didn't know globals were considered such bad practice, although they clearly mess things up – Luis Mendo Sep 01 '14 at 15:31
1

You can save the data in the local workspace into a .mat file, and return the mat file name as the output of your defined function. Then you use the load function in your calling function. Below gives the hints:

load(userConfig(configFile))

In the definition of your config function:

function output_args = userConfig(input_args)
...
run(input_args)
output_args = [input_args,'at'];
save(output_args)
end

I suppose the string configFile is your input_args of the userConfig function.

I just privide a solution that you may want, even though I do not recommend that.

Highman
  • 145
  • 6