container map repeated key in matlab

In MATLAB, the containers.Map class is used to create a map object where keys are unique. However, if you want to map repeated keys to multiple values, you can use cell arrays or structs as the values.

Here's an example of how you can map repeated keys to multiple values using cell arrays:

main.m
% Create a map object
myMap = containers.Map('KeyType', 'char', 'ValueType', 'any');

% Add values for a repeated key 'A'
myMap('A') = {1, 2, 3};

% Retrieve values for the key 'A'
valuesA = myMap('A');
disp(valuesA);
218 chars
10 lines

Output:

main.m
    [1]    [2]    [3]
22 chars
2 lines

In this example, the value for the key 'A' is a cell array containing three values: 1, 2, and 3. You can add or retrieve values for 'A' as needed.

Alternatively, you can also use structs as the values to map repeated keys:

main.m
% Create a map object
myMap = containers.Map('KeyType', 'char', 'ValueType', 'struct');

% Add values for a repeated key 'A'
myStruct1.field1 = 1;
myStruct1.field2 = 'Hello';

myStruct2.field1 = 2;
myStruct2.field2 = 'World';

myMap('A') = [myStruct1, myStruct2];

% Retrieve values for the key 'A'
valuesA = myMap('A');
disp(valuesA);
336 chars
16 lines

Output:

main.m
1x2 struct array with fields:
    field1
    field2
52 chars
4 lines

In this example, the value for the key 'A' is an array of structs, each containing two fields. You can access individual fields of each struct as needed.

Remember, when using cell arrays or structs as values in a map, you need to ensure consistent data structure for each key.

related categories

gistlibby LogSnag