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?
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.
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With