有没有办法在matlab中使用哈希表/ hashmaps? [英] Is there any way to use hashtables/hashmaps in matlab?

查看:2539
本文介绍了有没有办法在matlab中使用哈希表/ hashmaps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

MATLAB中的哈希表





一般问题



有没有办法在Matlab中获取一个hashset或者是hashmap结构?

General Question

Is there any way to get a hashset or hashmap structure in Matlab?

我经常发现自己处于需要查找唯一条目或检查向量成员资格的情况,并使用如 unique()或逻辑索引似乎通过向量搜索,并且对于大量的值来说真的很慢。在Matlab中最好的方式是什么?

I often find myself in situations where I need to find unique entries or check membership in vectors and using commands like unique() or logical indexing seems to search through the vectors and is really slow for large sets of values. What is the best way to do this in Matlab?

一个素数列表,并希望检查3是否为素数:

Say, for example, that I have a list of primes and want to check if 3 is prime:

primes = [2,3,5,7,11,13];

if primes(primes==3)
    disp('yes!')
else
    disp('no!')
end

如果我用长向量和多次事情变得很慢,

if I do this with long vectors and many times things get really slow.

所以基本上,python的 dict()或类似的Java的 java.util.HashSet java.util.HashMap ,在Matlab中?如果没有,是否有很好的方式在大型向量中进行查找?

So basically, is there any equivalents to python's set() and dict(), or similarly Java's java.util.HashSet and java.util.HashMap, in Matlab? And if not, is there any good way of doing lookups in large vectors?

这是我在答案中的建议的运行时间。

This is the running time i got on the suggestions in the answers.

>> b = 1:1000000;
>> tic; for i=1:100000, any(b==i);; end; toc
Elapsed time is 125.925922 seconds.

s = java.util.HashSet();
>> for i=1:1000000, s.add(i); end    
>> tic; for i=1:100000, s.contains(i); end; toc
Elapsed time is 25.618276 seconds.

>> m = containers.Map(1:1000000,ones(1,1000000));
>> tic; for i=1:100000, m(i); end; toc
Elapsed time is 2.715635 seconds

java集合的构造也很慢尽管如此,根据问题,这也可能相当缓慢。真的很高兴container.Map提示。它真的破坏了其他的例子,它也是即时设置的。

The construction of the java set was quite slow as well though so depending on the problem this might be quite slow as well. Really glad about the containers.Map tip. It really destroys the other examples, and it was instant in set up too.

推荐答案

像这样?

>> m = java.util.HashMap;
>> m.put(1,'hello,world');
>> m.get(1)
ans =
hello, world

如果你想要一个Matlab本地的实现,尝试

Alternatively, if you want a Matlab-native implementation, try

>> m = containers.Map;
>> m('one') = 1;
>> m('one')
ans =
     1

- 它将接受的唯一键是那些类型为 char 的键。您可以在创建地图时指定键值和值类型:

This is actually typed - the only keys it will accept are those of type char. You can specify the key and value type when you create the map:

>> m =  containers.Map('KeyType','int32','ValueType','double');
>> m(1) = 3.14;
>> m(1)
ans =
  3.14

您尝试放置除 int32 之外的任何键以及 double 之外的任何值。

You will now get errors if you try to put any key other than an int32 and any value other than a double.

您还可以使用套餐:

>> s = java.util.HashSet;
>> s.put(1);
>> s.contains(1)
ans = 
     1
>> s.contains(2)
ans = 
     0

这篇关于有没有办法在matlab中使用哈希表/ hashmaps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆