在 MATLAB 中重载运算符以模拟哈希数组
是否可以重载 subsref
和 subsasgn
以允许索引值使用非整数类型?
h = Hash; #% a custom hash class to manage my data
h(100) = 'data'; #% integer is fine, if index > 0
h{'string'} #% but this fails
??? Cell contents reference from a
non-cell array object.
有人能以某种方式破解它吗?
确切的解决方案:
containers.Map中有几个烦恼,可以通过创建一个继承它的自定义类来解决:
classdef Hash < containers.Map
# fun
end
在这样的类中,可以实现各种类型的键(不仅仅是一个!!)并且方便用户操作的方法。此外,还可以重新定义 subsref
和 subsasgn
以使用大括号和多个索引。好的!
Is it possible to overload subsref
and subsasgn
to allow non-integer types for index value?
h = Hash; #% a custom hash class to manage my data
h(100) = 'data'; #% integer is fine, if index > 0
h{'string'} #% but this fails
??? Cell contents reference from a
non-cell array object.
Can one hack it somehow?
Exact solution:
There are several annoyances in containers.Map
, which can be solved by making a custom class which inherits it:
classdef Hash < containers.Map
# fun
end
In such class one can implement various types of keys (not just one!!) and convenience methods for the user operations. Also it is possible to redefine subsref
and subsasgn
to work with curly braces and multiple indices. Nice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需破解。使用结构体或 containers.Map。它们是关联数组的原生 Matlab 数据结构。结构体由字符串索引(有一些限制)。 Containers.Map 可以通过字符串、非整数或其他数据类型进行索引。请参阅“帮助结构”和“帮助容器.Map”。 Map 使用括号进行索引,因此它的语法看起来像通过其他方式索引的数组。
No need to hack. Use a struct or a containers.Map. They are native Matlab data structures for associative arrays. A struct is indexed by strings (with some restrictions). A containers.Map can be indexed by string, non-integer numerics, or other data types. See "help struct" and "help containers.Map". The Map uses parentheses for indexing, so its syntax looks like an array indexed by other means.
为什么不只使用
java.util .HashMap
? Matlab 与 Java 配合得很好。 (虽然我猜这只适用于可以编组到 Java 中的数据,所以虽然矩阵和矩阵元胞数组都可以,但结构体已经过时了)啊哈:注意最后一点——Java 中数字和字符串的相等语义很简单,但对于数组来说,事情就变得棘手了,在 MATLAB 中使用 Java 有点像在手套箱中处理实验室样本。
如果您可以处理 java.util.HashMap 的限制(键相等语义、可在 Java 和 MATLAB 之间编组的类型限制),请使用它 - 否则您可能必须编写你自己的。
Why not just use a
java.util.HashMap
? Matlab works fine with Java. (Although I guess that only works with data that can be marshalled into Java, so although matrices and cell arrays of matrices are OK, structs are out)Aha: watch out for that last bit -- the equality semantics in Java for numbers and strings are straightforward, but for arrays, things get tricky, and using Java in MATLAB is a little like handling lab samples in a glove box.
If you can deal with the limitations of
java.util.HashMap
(key equality semantics, type limitations to those that can be marshalled between Java and MATLAB), use it -- otherwise you probably would have to write your own.