如何获取MATLAB句柄对象的ID?
当我尝试使用 MATLAB 句柄对象 作为键值时,问题就出现了在 MATLABContainers.Map 中。
ld( h1, h2 ) 定义了句柄对象的线性顺序,因此使用句柄对象作为映射的键值不应受到限制,但只允许整数或字符串类型。
此问题的解决方法可以是检索句柄对象的实际 ID(地址)(基本上在 ld 函数中进行比较)。
那么问题来了:如何获取句柄对象的ID?
发现可以使用静态成员函数中的持久变量来完成解决方法。
在这种情况下,您应该从基类继承所有类,如下所示。
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
结尾
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从未听说过像 Java/C# 中的对象
HashCode
这样的东西应用于 MATLAB OO。如果您获得 MATLAB 对象的地址(在命令窗口中键入format debug
),那么使用它仍然不合理,因为它不会像 C++ 中那样保持不变,而是会被系统移动(托管内存) )。您可以为 MATLAB 对象手动实现接口
getHashCode()
。与传统的哈希码不同,您必须确保不同对象的哈希码始终不同 - 这不是一个简单的任务!MATLAB 默认比较器函数
sort
显然在内部使用对象哈希码,但这对您没有帮助 - 比较对象实际上是与其哈希码正交的概念。I have never heard of something like object
HashCode
in Java/C# applied to MATLAB OO. If you get address of a MATLAB object (typeformat 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.