How to know and use the unknown variables loaded in main program from .m files

1 view (last 30 days)
I searched for this a lot on internet but didn't find this particular problem. There is a .m file which contains a single matrix of data defined inside it by a variable, like a = [1,2,3...]. The main program loads this file and doesn't know about the name of variable 'a'. So how do I use this unknown variable?

Answers (2)

Walter Roberson
Walter Roberson on 13 Oct 2015
You cannot distinguish between such a variable and any variable you might have defined before you called the .m file. The solution is not to write .m files as scripts: write them as functions.
If you are magically certain that the variable name does not clash with the name of any variable you defined before you called the .m file, then you can use who() or whos() to get the names of the variables in your workspace, and then remove from the list the variables that you know you created yourself. If there is a single variable left over then it is the one you want.
But how are you going to access the variable once you know its name? Our answer is "Don't do that!"

Image Analyst
Image Analyst on 13 Oct 2015
You need to have the m-file be a function that returns the value "a" that it creates:
In your main program, MainProgram.m:
function MainProgram()
result = MyFunction() % MyFunction creates "a"
In your other m-file, make it a function, not a script by putting the function work there and having it return "a:. So MyFunction.m would contain:
function a = MyFunction()
a = [1, 2, 3];
% Some more code...whatever...
Now, "result" in the main program will be the same values as "a" in MyFunction().

Community Treasure Hunt

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

Start Hunting!