Sunday, April 15, 2007

Matlab and hash tables

Unfortunately, Matlab does not have hash table functionality by itself. However, Matlab is based on Java, and provides programing interface to java classes. Consequently, it is possible to use Hash tables from Java!. It can be convenient and fast. You can store normal scalars, strings, matrices, etc in Java containers without much effort.
Below little example just to start with. It shows Hashtable, where we put few values, and afterwards we create iterator and iterate over Hashtable.

function testJavaHash
import java.util.*;
ja_h = Hashtable;

a='aaa';
b=12.23;
c=[1 2; 3 4];
s='marcin';

%add something to hash
ja_h.put(1,a);
ja_h.put(2,b);
ja_h.put(3,c);
ja_h.put(s,c);


%create iterator;
keys = ArrayList(ja_h.keySet( ));
iterator = keys.iterator();


%iterate over all keys
while iterator.hasNext()
key=iterator.next();
val=ja_h.get(key);
key
val
end

Unfortunately, it is not as nice as it looks like. For example it is not possible to use matrices as keys in hash tables. For instance:
ja_h.put([1 2],2);
ja_h.get([1 2])
ans =

[]
As it can be seen, ja_h.get returns nothing.
What I do do overcome this, I just convert matrix into string with num2str and back str2num. Not the best possible solution but it works for me in few limited situations:
ja_h.put(num2str([1 2]),2);
ja_h.get(num2str([1 2]))
ans =

2
However this solution does not work for e.g. 2x2 matrices ja_h.put(num2str([1 2; 3 4]),2);
ja_h.get(num2str([1 2; 3 4]))
ans =

[]
Similar problems are with mhashtable package available from Matlab Central File Exchange. I do not know why it is so difficult for Matlab engineers to create native Matlab support for Hash tables?