How can the variable "var", included in a MAT-file, be loaded under a different name?
I have a few MAT-files which include a variable whose name is always the same, but the value is of course different. I want to load them through a loop without rewriting them in each iteration, so I need to change their name just before loading them. Is that possible?
Renaming a variable within the saved workspace and then loading it is also a solution. Is this other strategy possible?
Instead of littering your workspace with lots of renamed variables (like var_1
, var_2
, etc.), I would suggest storing your loaded data in some form of array (numeric, cell, or structure). This will generally make it a lot easier to organize and process your data. Here's an example of loading the data into a structure array, using 3 MAT-files that each store the variable var
with different values (1, 2, and 3):
fileNames = {'file1.mat'; 'file2.mat'; 'file3.mat'};
for iFile = 1:numel(fileNames)
structArray(iFile) = load(fileNames{iFile}, 'var');
end
And structArray
will be an array of structure elements containing data in the field var
:
>> structArray
structArray =
1×3 struct array with fields:
var
Now, you can extract the field values and put them in a numeric array like so:
>> numArray = [structArray.var]
numArray =
1 2 3
Or, if they are different sizes or data types, place them in a cell array:
>> cellArray = {structArray.var}
cellArray =
1×3 cell array
[1] [2] [3]