How to use Hash Tables (dictionaries) in MATLAB?

50,379

Solution 1

In recent versions of MATLAB, there's the containers.Map data structure. See MATLAB Map containers for more. This removes some of the restrictions when using STRUCTs. For example

c = containers.Map
c('foo') = 1
c(' not a var name ') = 2
keys(c)
values(c)

Solution 2

A structure can be used as a sort of hash table:

>> foo.('one')=1

foo = 

    one: 1

>> foo.('two')=2;
>> x = 'two';
>> foo.(x)

ans =

     2

To query whether a structure contains a particular field (key), use isfield:

>> isfield(foo,'two')

ans =

     1

The disadvantage of this scheme is that only strings that are also valid Matlab variable names can be used as keys. For instance:

>> foo.('_bar')=99;
??? Invalid field name: '_bar'.

To get around this restriction, use one of the solutions in the question linked by Oli.

Share:
50,379

Related videos on Youtube

NoobDev4iPhone
Author by

NoobDev4iPhone

Updated on July 09, 2022

Comments

  • NoobDev4iPhone
    NoobDev4iPhone almost 2 years

    I need to acces data by string index, like table('one') %returns 1. Is there such a data structure in MATLAB? How is it implemented?

  • rhombidodecahedron
    rhombidodecahedron about 9 years
    Another disadvantage of this approach is that the names of the keys have to be less than namelengthmax (63) characters