Dictionaries and Custom Classes - MATLAB & Simulink (original) (raw)
Main Content
One benefit of the dictionary data type is the ability to accept almost any data type, including custom classes. In some cases however, the behavior of custom classes affects how they interact with dictionaries. This example shows how to overload two key functions for custom classes to make sure that dictionaries behave as expected.
Hash Equivalence
Dictionaries are hash maps, meaning that they convert keys intouint64
scalar hash codes. Each hash code represents a unique key and is used during lookup to quickly find the requested value. In MATLABĀ®, these scalars are generated using the keyHash function, which uses input property information to generate a uint64
scalar. The keyMatch function can be used to determine whether hashed keys are equivalent. For a dictionary to function properly, when keyMatch(A,B)
is true, thenkeyHash(A)
and keyHash(B)
must be equal. For most data types, this relationship holds true without any extra steps. However, some custom classes can have properties that you do not want to include as part of the comparison.
For example, create a class that is used to collect data and record the time that the data was collected. This class has two properties dataValue
andtimestamp
.
classdef myDataClass properties dataValue double = 0 timestamp datetime = datetime end end
For the purposes of comparing data, only dataValue
is important. However, keyHash
uses both properties when generating a hash code.
Overload keyHash
and keyMatch
for Custom Classes
To make myDataClass
work as intended with dictionaries, overloadkeyHash
and keyMatch
. AddkeyHash
and keyMatch
methods tomyDataClass
that use only the dataValue
property to generate and compare hash values.
classdef myDataClass properties dataValue double = 0 timestamp datetime = datetime end methods function h = keyHash(obj) h = keyHash(obj.dataValue); end function tf = keyMatch(objA,objB) tf = keyMatch(objA.dataValue,objB.dataValue); end end end
See Also
dictionary | keyHash | keyMatch