Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary for-loop matlab

Store values from a MATLAB for loop similar to a Python dictionary

发布于 2020-03-28 23:16:30

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

Questioner
anarz
Viewed
107
Wolfie 2020-01-31 18:05

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.