Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a MATLAB dictionary like in Python [duplicate]

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, ...}
like image 547
Lucas Avatar asked May 17 '26 07:05

Lucas


2 Answers

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.

like image 106
Luis Mendo Avatar answered May 22 '26 02:05

Luis Mendo


MATLAB R2022b has a new dictionary datatype that is significantly better than containers.Map. A tutorial describing it can be found on The MATLAB blog https://blogs.mathworks.com/matlab/2022/09/15/an-introduction-to-dictionaries-associative-arrays-in-matlab/

For example:

names = ["Mike","Dave","Bob"];
weights = [89,75,68]; % weight in kilograms
gym = dictionary(names,weights) % Vectorised constructor. Performs elementwise mapping.

gives

gym = 

      dictionary (string ⟼ double) with 3 entries:
    
        "Mike" ⟼ 89
        "Dave" ⟼ 75
        "Bob"  ⟼ 68
like image 40
WalkingRandomly Avatar answered May 22 '26 02:05

WalkingRandomly