Multiple numerics as one map key / Merge Objects based on parameters

1 回表示 (過去 30 日間)
Jan Siegmund
Jan Siegmund 2020 年 7 月 3 日
回答済み: Jan Siegmund 2020 年 7 月 3 日
I want to use two numerics as a single key for a map to merge similar objects of a class. How can I do that?
My class looks like this:
classdef Foo
properties
a double
b double
val double
end
methods
function obj = Foo(a,b,val)
obj.a = a;
obj.b = b;
obj.val = val;
end
function o = plus(l,r)
o = Foo(l.a,l.b,l.val+r.val);
end
function k = getKey(obj)
<...>
end
end
end
The code should do the following:
fooCell = {Foo(3,4,100) Foo(3,4,20) Foo(2,5,20)};
fooMap = containers.Map('KeyType', <...> ,'ValueType','any');
for i=1:length(fooCell)
k = fooCell{i}.getKey;
if fooMap.isKey(k)
fooMap(k) = fooMap(k)+fooCell{i};
else
fooMap(k) = fooCell{i};
end
end
fooMap.values %Should contain 2 objects: Foo(3,4,120) & Foo(2,5,20)
How should the getKey method look like?

採用された回答

Jan Siegmund
Jan Siegmund 2020 年 7 月 3 日
The only keytype which can hold two doubles is the character key type. So one may use char as key type and then simply
function k = getKey(obj)
k = num2str([obj.a obj.b],'%d');
end
An even faster approach could be
function k = getKey(obj)
k = char(typecast([obj.a obj.b],'uint16'));
end
As every char in MATLAB is 16bit. This may produce non-printable keys though.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by