containers with repeated key in matlab

In Matlab, containers like structs and tables cannot have repeated keys. Each key must be unique within the container.

However, if you want to store multiple values for the same key, you can achieve this by using cell arrays.

Here is an example of how you can use a cell array to store multiple values for the same key:

main.m
% Create a cell array to store values for each key
myContainer = containers.Map();

% Add values to the container
key = 'fruit';

if isKey(myContainer, key)
    % If the key already exists, append the new value to the existing array
    valueArray = myContainer(key);
    valueArray{end+1} = 'banana';  % add a new value
    myContainer(key) = valueArray; % update the container with the new value
else
    % If the key does not exist, create a new array with the value
    valueArray = {'apple'};
    myContainer(key) = valueArray;
end

% Access the values for a key
values = myContainer(key);

% Display the values
disp(values);
631 chars
23 lines

Output:

main.m
    'apple'    'banana'
24 chars
2 lines

In this example, we use the containers.Map() function to create a container object. We check if the key already exists using the isKey() function. If the key exists, we retrieve the existing values, add the new value to the array, and update the container. If the key does not exist, we create a new array and add it to the container with the new value.

This way, you can store multiple values for the same key using the cell arrays in Matlab.

related categories

gistlibby LogSnag