Summation of Container Values

1 visualización (últimos 30 días)
Tingjun Wu
Tingjun Wu el 12 de Nov. de 2019
Respondida: Abhisek Pradhan el 21 de Nov. de 2019
How can I sum the Container values?
example:
I have Container A and B
A = containers.Map({'W', 'C'},[1,2]);
B = containers.Map({'W', 'Co'},[3,4]);
And I want sum A and B
So the result should be:
W: 4
C: 2
Co: 4
How can I do that?

Respuestas (1)

Abhisek Pradhan
Abhisek Pradhan el 21 de Nov. de 2019
The code below provides a generalized approach to merge maps and if there is a collision because of same key add those values.
allKeys0 = cellfun(@keys, maps, 'UniformOutput', false);
[allKeys, ~, m] = unique([allKeys0{:}]);
allValues0 = cellfun(@values, maps, 'UniformOutput', false);
allValues = cell2mat([allValues0{:}]);
sumValues = arrayfun(@(x) sum(allValues(m==x)), 1:numel(allKeys));
mergedMap = containers.Map(allKeys, sumValues);
Refer the link below for more information on MATLAB map container.

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by