0

I am looping through files (using for loop) and getting two values from each loop - name and tag. What is the best way to store these values, if I later want to access tags using names?

  1. Is there anything similar to python dictionary: {'name1': tag1, 'name2': tag2, .... 'nameN': tagN}

  2. Or should it be stored in a table with two columns - name and tag

Thanks

Wolfie
  • 27,562
  • 7
  • 28
  • 55
anarz
  • 209
  • 4
  • 11
  • The closest thing to dictionaries in MATLAB, I can think of, are [Map Containers](https://www.mathworks.com/help/matlab/map-containers.html). – HansHirse Jan 31 '20 at 09:54
  • 1
    Also: Does this answer your question? [Create a MATLAB dictionary like in Python](https://stackoverflow.com/questions/56804013/create-a-matlab-dictionary-like-in-python) – HansHirse Jan 31 '20 at 10:06

1 Answers1

1

Sounds like you want containers.Map

You can store the name/value pairs in a cell array, then stick these into a map for later reference

% Create loop data
N = 10;
data = cell(N,2);
for ii = 1:N 
    data{ii,1} = sprintf( 'Name%.0f', ii );
    data{ii,2} = sprintf( 'Tag%.0f', ii );
end
% Create map
m = containers.Map( data(:,1), data(:,2) );

You can then evaluate this in two ways

% For a single value
m( 'Name1' ) % = 'Tag1';
% For one or more values
m.values( {'Name1','Name2'} ) % = {'Tag1','Tag2'};

The only real advantage of using a map here is syntax unless your data especially lends itself to being in this structure. It isn't much harder to just use logical indexing once you have the data array

data( ismember(data(:,1), 'Name1'), 2 ) % = {'Tag1'}

You could even make an anonymous function as shorthand for this operation (after defining data), which saves requiring the .values syntax used by maps

f = @(str) data( ismember( data(:,1), str ), 2 );
f( 'Name1' ) % = {'Tag1'}
f( {'Name1','Name2'} ) % = {'Tag1','Tag2'}

Note that the ismember approach will not throw an error if your 'NameX' is not found, whereas the map will throw an error if the key doesn't exist.

Wolfie
  • 27,562
  • 7
  • 28
  • 55