Is there a comand to select variables with a specific name from workspace

2 views (last 30 days)
I have the following problem:
I have a loop which loads files X Y Z from different matfiles so that I have the files X Y Z in the workspace as well as a variable loaded_files = {'X', 'Y', 'Z'}.
Now I want to create a Matrix XYZ = [X; Y; Z] in an automated way like this: XYZ = [loaded_files].
The names of the variables to concatenate are actually listed in the variable loaded_files. Is ther a command which allows that?

Accepted Answer

Guillaume
Guillaume on 6 Dec 2016
Much safer would be using the form of load that load the mat file into fields of a structure (by simply giving an output variable to load). This avoid the risk of overwriting essential variables. In your case, if one of these mat file accidentally contain a loaded_files variable, your code will fail.
It's also more practical for your purpose:
%loading the mat files. Taking a guess at your code
%filestoload: cell array of mat file names
filecontents = cell(size(filestoload)); %allocate cell array to store structures returned by load
for fileidx = 1:numel(filestoload)
filecontents{filedix} = load(filestoload{fileidx});
end
%concatenating relevant variables
%loaded_variables = {'X', 'Y', 'Z'}; %loaded_variables is a better name than loaded_files
xyz = [];
for fileidx = 1:numel(filestoload)
xyz = [xyz; filecontents{fileidx}.(loaded_variables{filedix})];
end
The above relies on the fact that you can generate structure field names from variables

More Answers (0)

Categories

Find more on Matrices and Arrays 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!