Krystian Meresiński
Krystian Meresiński

Reputation: 85

Use a content of a cell as a variable name

I've created cell full of string variables:

X{1,1} = 'TEST1A1'
X{2,1} = 'TEST1A2'
X{3,1} = 'TEST1A3'
...
X{120,1} = 'TEST8C5'

Each of them represent set of data from an experiment. I'm creating a set of 3Dmatrix containing that data and it would be great if I could use those strings as a variable names.

Would a function handle be the solution for this? I've never really used them before.

Upvotes: 1

Views: 175

Answers (1)

gire
gire

Reputation: 1105

One option would be to use a structure with dynamic field names.

To fill it up:

X = {'test1', 'test2', 'test3', ...};
my_data = struct();

for t = 1:length(X)
    my_data.(X{t}) = <<read test "t" from file or database function + parameters>>
end

You will end up with a structure like this:

my_data.test1 % //(contains a 2d or 3d matrix for test 1)
my_data.test2 % //(contains a 2d or 3d matrix for test 2)
...

To read dynamically you do the same:

% // read only one member
tmp = my_data.(X{2})

% // or read them sequentially
for t = 1:length(X)
    tmp = my_data.(X{t})

    % // do something with tmp
end

I certainly consider the structure with dynamic fields cleaner than the trick of using the eval function:

eval([X{1}, ' = <<read test "1" from file or database function + parameters>>']);

Upvotes: 2

Related Questions