I would like to know if there exists a way in MATLAB to create a dictionary like in Python.
I have several Port Name and Port Type and I would like to create a dictionary like this :
dict = {PortName : PortType, PortName : PortType, ...}
EDIT: Since R2022b Matlab has a dictionary
type, which is recommended over containers.Map
.
The closest analogy is containers.Map
:
containers.Map
: Object that maps values to unique keys
The keys are character vectors, strings, or numbers. The values can have arbitrary types.
To create the map you pass containers.Map
a cell array of keys and a cell array of values (there are other, optional input arguments):
>> dict = containers.Map({ 'a' 'bb' 'ccc' }, { [1 2 3 4], 'Hey', {2 3; 4 5} });
>> dict('a')
ans =
1 2 3 4
>> dict('bb')
ans =
'Hey'
>> dict('ccc')
ans =
2×2 cell array
{[2]} {[3]}
{[4]} {[5]}
You can also append key-value pairs to an existing map:
>> dict('dddd') = eye(3);
>> dict('dddd')
ans =
1 0 0
0 1 0
0 0 1
However, depending on what you want to do there are probably more Matlab-like ways to do it. Maps are not so widely used in Matlab as dictionaries are in Python.