How to use Hash Tables (dictionaries) in MATLAB?

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)

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.

Tags:

Matlab