问题
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, ...}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/56804013/create-a-matlab-dictionary-like-in-python