gzm0
gzm0

Reputation: 14842

Merge cell array of maps by key in Matlab

Given a cell array of containers.Map objects containing counts (values) for given events (keys). I would like to get a single map containing the sum of the counts (as values) for each key (or something allowing me to calculate the counts).

For example:

maps = { containers.Map({'a','b'},{1,2}),
         containers.Map({'b','c'},{4,1}) };

mergeMaps(maps)

  ans = Map(a -> 1, b -> 6, c -> 1)

The only thing I could come up with so far is:

maps = { ... };
res = containers.Map();
for cMapC = maps
    cMap = cMapC{1};
    for cKeyC = keys(cMap{1})
        cKey = cKeyC{1};
        if isKey(res, cKey)
            res(cKey) = res(cKey) + cMap(cKey);
        else
            res(cKey) = cMap(cKey);
        end
    end
end

Which should work (untested), but whose "efficiency" and readability is questionable to say the least. What is a better solution?

Please note that currently there is no index attributed to events, so using sparse matrices instead of maps is cumbersome.

Upvotes: 3

Views: 1040

Answers (1)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

Not sure about readability, but it is probably more efficient:

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);

Upvotes: 5

Related Questions