开发者

Overloading operators in MATLAB to emulate hash-array

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!


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.

>> m = containers.Map(.1, 'myvalue');
>> m(.75) = 'anothervalue';
>> x = m(.1)
x =
myvalue
>> 


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)

>> x = java.util.HashMap;
>> x.put(3, [1 2 3]);
>> x.put('Rosebud',[4 5 6; 7 8 9]);
>> x.put([2 4 6 8],'Michaelangelo'); 
>> x.get(3)

ans =

     1
     2
     3

>> x.get('Rosebud')

ans =

     4     5     6
     7     8     9

>> x.get([2 4 6 8])

ans =

     []

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜