Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Hash Tables (dictionaries) in MATLAB? [duplicate]

Tags:

matlab

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?

like image 329
NoobDev4iPhone Avatar asked Mar 24 '12 07:03

NoobDev4iPhone


People also ask

Are hash tables and dictionaries the same?

A dictionary is a data structure that maps keys to values. A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values are stored.

Do dictionaries use hash tables?

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs. Dictionary is generic type, hash table is not a generic type. The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable.

What is Dict in Matlab?

DICT is a general purpose data storage object similar to the DICT object in Python. Data is stored as key/value pairs. Keys and values can be any Matlab data type.

What is a hash data structure?

What is Hashing in Data Structure? Hashing in the data structure is a technique of mapping a large chunk of data into small tables using a hashing function. It is also known as the message digest function. It is a technique that uniquely identifies a specific item from a collection of similar items.


2 Answers

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)
like image 182
Edric Avatar answered Oct 01 '22 19:10

Edric


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.

like image 26
nibot Avatar answered Oct 01 '22 19:10

nibot