Search code examples
excelmatlabvariablesworkspace

Accessing Matlab Workspace Variables with Dynamic Names


Quick Question.

I have an excel file which lists varying names. I import those names into Matlab, perform calculations, and then save the data as a .dat file.

For example:

Apple.dat: 2, 5, 50, 2993
Orange.dat: 5003, 292, 29, 2994
Banana.dat: 3992, 3, 39, 2995

I then read each individual .dat file with eval and load the data/matrices as individual variables into the main Workspace. At this point I have all the variables in WorkSpace as well as a cell file which contains this list (ListofVariables).

My main goal is to access each of the variables without knowing their name - because my excel document will change over time! However, if I type:

ListofVariables(i,1)

It will only pull up 'Apple', and not the data associated with variable Apple. Is there to access the variables' data without knowing their individual names?

Thank you for your help!


Solution

  • You can use eval:

    %// Simulate loading .dat files
    apple = [2 5 50 2993];
    orange = [5003 292 29 2994];
    banana = [3992 3 39 2995];
    
    ListofVariables = {'apple', 'orange', 'banana'};
    
    %// load data to a structure    
    data = [];
    for k=1:numel(ListofVariables)
        name = ListofVariables{k};
        data = setfield(data, name, eval(name));
    end
    %//The data from all files is in the structure data
    
    %// load data to a cell
    data = {};
    for k=1:numel(ListofVariables)
        name = ListofVariables{k};
        data(end+1) = eval(name);
    end
    %//The data from all files is in the cell (the names are lost, but you can access them by index, using the same order as ListofVariables)