container repeated key in matlab

Unfortunately, it is not possible to have a container with repeated keys in MATLAB. The keys in MATLAB containers, such as containers.Map or table, must be unique. If you attempt to insert an element with a key that already exists, it will either overwrite the previous value or raise an error, depending on the container type.

If you need to store multiple values for a single key, you can use cell arrays or struct arrays.

Here is an example using a cell array:

main.m
% Create a cell array to store values for each key
container = {};

% Add values to the container
key = 'A';
value1 = 10;
value2 = 20;
container{end+1} = {key, value1};
container{end+1} = {key, value2};

% Retrieve values for a key
key = 'A';
values = container(cellfun(@(x) strcmp(x{1}, key), container));
307 chars
14 lines

In this example, the container is a cell array, where each element is a cell array containing the key and value pair. To retrieve the values for a specific key, you can iterate over the container and filter the elements based on the desired key.

Alternatively, you can use struct arrays to achieve a similar effect. Each field of the struct array can represent a key, and the corresponding values can be stored as an array or cell array within that field.

related categories

gistlibby LogSnag