1

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?

gnovice
  • 125,304
  • 15
  • 256
  • 359
Peter
  • 71
  • 6
  • So would you rename all the variables ('var') something else for each loop? var_1, var_2, var_3 etc etc.... so you can later reuse these variables? – Flynn Jul 24 '17 at 20:19
  • Yes! The idea is to not rewrite in the second iteration the loaded variable in the first iteration (they all have the same name) – Peter Jul 24 '17 at 20:24
  • 1
    Well I don't think it's good practice, but you can use eval to set each variable name like I mentioned above, based on your iteration. like when i=1, then you would do eval(['var_',num2str(i),'=var']); Because all the variable represent the same thing, I would look into concatenating them or creating a cell Like @gnovice mentions below. – Flynn Jul 24 '17 at 20:26

1 Answers1

3

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]
gnovice
  • 125,304
  • 15
  • 256
  • 359