poster
2019-12-10, 20:48
是否可以重载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以使用花括号和多个索引。真好!
回答:
无需黑客。使用struct或container.Map (http://www.mathworks.com/help/techdoc/ref/containers_map.html) 。它们是用于关联数组的本机Matlab数据结构。结构由字符串索引(有一些限制)。可以通过字符串,非整数数字或其他数据类型来索引container.Map。请参阅“帮助结构”和“帮助容器。地图”。 Map使用括号进行索引,因此其语法看起来像是通过其他方式索引的数组。
>> m = containers.Map(.1, 'myvalue'); >> m(.75) = 'anothervalue'; >> x = m(.1) x = myvalue >>
更多&回答... (https://stackoverflow.com/questions/4430467)
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以使用花括号和多个索引。真好!
回答:
无需黑客。使用struct或container.Map (http://www.mathworks.com/help/techdoc/ref/containers_map.html) 。它们是用于关联数组的本机Matlab数据结构。结构由字符串索引(有一些限制)。可以通过字符串,非整数数字或其他数据类型来索引container.Map。请参阅“帮助结构”和“帮助容器。地图”。 Map使用括号进行索引,因此其语法看起来像是通过其他方式索引的数组。
>> m = containers.Map(.1, 'myvalue'); >> m(.75) = 'anothervalue'; >> x = m(.1) x = myvalue >>
更多&回答... (https://stackoverflow.com/questions/4430467)