如何在MATLAB中使用哈希表(字典)?

时间:2012-03-24 07:41:49

标签: matlab

我需要通过字符串索引访问数据,例如 表('one')%返回1 。 MATLAB中是否有这样的数据结构?它是如何实现的?

3 个答案:

答案 0 :(得分:53)

在最近的MATLAB版本中,有containers.Map数据结构。有关详情,请参阅MATLAB Map containers。这样可以消除使用STRUCT时的一些限制。例如

c = containers.Map
c('foo') = 1
c(' not a var name ') = 2
keys(c)
values(c)

答案 1 :(得分:17)

结构可以用作一种哈希表:

>> foo.('one')=1

foo = 

    one: 1

>> foo.('two')=2;
>> x = 'two';
>> foo.(x)

ans =

     2

要查询结构是否包含特定字段(键),请使用isfield

>> isfield(foo,'two')

ans =

     1

这种方案的缺点是只有作为有效Matlab变量名的字符串才能用作键。例如:

>> foo.('_bar')=99;
??? Invalid field name: '_bar'.

要解决此限制,请使用Oli链接的问题中的一种解决方案。

答案 2 :(得分:0)

只需添加到先前的答案(无法对其他好的答案进行评论):这样的结构查找:

s={};
s.abc = 1;   %insert a value in the struct, abc is your lookup hash
out = s.abc; % read it back

使用结构,实际读回值比使用容器快大约10倍。完整的测试代码如下:

function s=test_struct_lookup_hash_speed
%% test how a struct lookup speed works vs container, interesting

    s = {};  % hash table
    v = {};  % reverselookup table for testing

    nHashes = 1E4;  % vary this to see if read speed varies by size (NOT REALLY)
    nReads  = 1E6;

    fprintf('Generating hash struct of %i entries\n', nHashes);
    tic
    for i = 1:nHashes
        hashStr = md5fieldname(randi(1E8));
        s.(hashStr) = i;
        v{end+1} = hashStr;  %reverselookup
    end
    toc

    fprintf('Actual HashTable length (due to non unique hashes?): %i, and length of reverse table: %i\n',length(fieldnames(s)), length(v) );

    fprintf('Reading %i times from a random selection from the %i hashes\n', nReads, nHashes);
    vSubset = [ v(randi(nHashes,1,3))  ];

    for i = 1:length(vSubset)
       hashStr = vSubset{i};

       % measure read speed only
       tic
       for j = 1:nReads
         val = s.(hashStr);
       end
       toc

    end


    %% test CONTAINERS
    fprintf('Testing Containers\n');
    c = containers.Map;

    fprintf('Generating hash struct of %i entries\n', nHashes);
    tic
    for i = 1:nHashes
        hashStr = md5fieldname(randi(1E8));
        c(hashStr) = i;
        v{end+1} = hashStr;  %reverselookup
    end
    toc

   fprintf('Reading %i times from a random selection from the %i hashes\n', nReads, nHashes);
   vSubset = [ v(randi(nHashes,1,3))  ];

    for i = 1:length(vSubset)
       hashStr = vSubset{i};

       % measure read speed only
       tic
       for j = 1:nReads
         val = c(hashStr);
       end
       toc

    end    



    %% Get a valid fieldname (has to start with letter)   
    function h=md5fieldname(inp)
    h = ['m' hash(inp,'md5')];
    end


end