1

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, ...}
Cris Luengo
  • 49,445
  • 7
  • 57
  • 113
Lucas
  • 197
  • 1
  • 12

2 Answers2

5

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.

Luis Mendo
  • 109,078
  • 12
  • 70
  • 142
  • Thanks ! And is it possible to append key and value to the `containers.map ` ? For example : `for port in a Simulink system => i append name as key and type as value` – Lucas Jun 28 '19 at 09:17
  • Thanks you, that's perfect – Lucas Jun 28 '19 at 09:34
5

You can use containers.Map as suggested by Luis Mendo in the other answer, but I think in this case a struct is much simpler:

>> dict = struct('a',[1 2 3 4], 'bb','Hey', 'ccc',{2 3; 4 5});
>> dict.('a')
ans =
     1     2     3     4
>> dict.a
ans =
     1     2     3     4
>> dict.b
ans =
    'Hey'
>> dict.ccc
ans =
  2×2 cell array
    {[2]}    {[3]}
    {[4]}    {[5]}

>> dict.dddd = eye(3);
>> dict.('eee') = eye(3);
>> dict.dddd
ans =
     1     0     0
     0     1     0
     0     0     1

That is, the struct is always indexed using .('name') or simply .name. But there are restrictions on what 'name' can be (it must be a valid variable name), unlike for the Map.

See this other answer to learn about important differences between the two approaches.

Cris Luengo
  • 49,445
  • 7
  • 57
  • 113
  • A sparse array is another option if your keys are unsigned integers and values are numbers. – pavon Nov 01 '21 at 20:14