Dictionaries and Custom Classes
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.
Dictionaries are hash maps, meaning that they convert keys into
uint64 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
function, which uses input property information to generate a
function can be used to determine whether hashed keys are equivalent. For a dictionary to
function properly, when
keyMatch(A,B) is true, then
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
classdef myDataClass properties dataValue double = 0 timestamp datetime = datetime end end
For the purposes of comparing data, only
dataValue is important.
keyHash uses both properties when generating a hash
keyMatch for Custom Classes
myDataClass work as intended with dictionaries, overload
keyMatch methods to
myDataClass that use only the
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