How to get the ID of MATLAB handle object?

2019-04-29 16:22发布

问题:

The problem comes when I am trying to use MATLAB handle objects as key values in MATLAB containers.Map.

ld( h1, h2 ) defines a linear order on handle objects, so there should be no limitation on using handle objects as key values for maps, however only integer or string types are allowed.

A workaround for this problem could be retrieving the actual ids (addresses) of handle objects (which are basically being compared in ld function).

So the question is: how to get the ID of a handle object?


Found out that a workaround can be done using persistent variables in static member functions.

In this case you should inherit all your classes from a base class like the following.

classdef object < handle
properties ( GetAccess = 'public', SetAccess = 'private' )
    id
end

methods ( Access = 'protected' )
    function obj = object()
        obj.id = object.increment();
    end
end

methods ( Static, Access = 'private' )
    function result = increment()
        persistent stamp;
        if isempty( stamp )
            stamp = 0;
        end
        stamp = stamp + uint32(1);
        result = stamp;
    end
end  

end

回答1:

I have never heard of something like object HashCode in Java/C# applied to MATLAB OO. If you get address of a MATLAB object (type format debug in the command window) it is still not reasonable to use it because it will not stay same unlike in C++ but will be moved by system (managed memory).

You could manually implement an interface getHashCode() for your MATLAB objects. Unlike traditional hashcode you must make sure that your hashcode is always different for different objects - not a simple task!

MATLAB default comparer function sort apparently uses internally the object hashcode but this will not help you here - comparing objects is actually an orthogonal concept to their hashcode.