hash表 matlab,matlab中hash和map的用法总结

若要在matlab中使用hash,有两种方式:

(1)采用matlab官方给出的结构类型map(containers.Map):

http://cn.mathworks.com/help/matlab/map-containers.html

(2)调用Java中的hashmap或者hashtable

(2.1)hashtable的具体示例:

http://blog.csdn.net/chaosstar/article/details/8268602

哈希表是一种很有用的数据结构,其可由关键字(key)直接定位到数据值(value);在很多应用中,使用哈希表可以方便高效地达到目的。

但哈希表并不是matlab内置数据类型,所以要在matlab中使用哈希表就比较麻烦了;幸好,matlab提供了一种调用Jave哈希表的方法,让我们可以间接的使用哈希表。

废话少说,直接上代码:

-------------------------------------------------------------------

%以下代码功能为:统计文本中单词出现的次数(包括数字,但不包括标点)

text ='In computing, a hash table (also hash map) is a datastructure used to implement an associative array, a structure that can map keysto values. A hash table uses a hash function to compute an index into an arrayof buckets, from which the correct value can be found.';

word_cell = regexp(text,'\w+','match');%使用正则表达式分割文本中的字符

word_ht = java.util.Hashtable;%生成哈希表的对象

%遍历文本单词cell,并统计单词出现次数

forii =1: length(word_cell)

lower_word = lower(word_cell{ii});%转换为小写字符

if word_ht.containsKey(lower_word)%单词是否已在关键字列表中

word_ht.put(lower_word, word_ht.get(lower_word)+1);%使用ht.put(key, value)将单词及其出现次数保存到哈希表中

else

word_ht.put(lower_word,1);

end

end

word_list = word_ht.keys;%获取关键字列表

%输出所有单词及其出现次数(并无排序)

while(word_list.hasNext )% word_list.hasNext为真说明下一个元素存在,否则已遍历到列表尾

word = word_list.nextElement;%获取下一个关键字

fprintf('%s : %d\n', word, word_ht.get(word));%使用ht.get(key)可得到key对应的value,即value = ht.get(key)

end

-------------------------------------------------------------------------------------------

(2.2)hashmap具体示例:

http://blog.chengsite.com/?p=345​

注意:

hashtable、hashmap和map的区别还是有不少的,比如内存机制不同,对于较大规模数据,用hash效率更高。

参考:http://www.cnblogs.com/lidabo/archive/2013/08/12/3253045.html​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值