一种更快的方法来实现intersect()给我什么? [英] a faster way to achieve what intersect() is giving me?

查看:166
本文介绍了一种更快的方法来实现intersect()给我什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码中花费了很多时间:

I am finding that a lot of time spent in my matlab function is in this code:

intersect(freq_bins, our_bins);

两者都可以是相当大的向量,并且仅由整数组成.我只需要知道两者中都包含哪些整数.这确实是intersect()的原始目的,因此我怀疑答案是:它不会变得更好.但是也许有人有一些建议.

Both can be rather large vectors, and are comprised of only integers. I just need to know which integers are in both. This is truly the primitive purpose of intersect(), so I suspect that the answer is: it doesn't get any better. But maybe someone has some suggestions.

推荐答案

intersect调用ismember.就您而言,您不需要intersect所做的所有复杂检查,因此您可以节省一些开销并直接调用ismember(注意:我确保在对它们进行定时之前都调用了这两个函数):

intersect calls ismember. In your case, you don't need all the complicated checks that intersect does, so you can save some overhead and call ismember directly (note: I made sure to call both functions before timing them):

a = randi(1000,100,1);
b = randi(1000,100,1);

>> tic,intersect(a,b),toc
ans =
    76
   338
   490
   548
   550
   801
   914
   930
Elapsed time is 0.027104 seconds.

>> tic,a(ismember(a,b)),toc
ans =
   914
   801
   490
   548
   930
   550
    76
   338
Elapsed time is 0.000613 seconds.

您可以通过直接调用进行实际测试的函数ismembc来使其更快.请注意,ismembc需要排序数组(因此,如果输入已经排序,则可以删除排序!)

You can make this even faster by calling ismembc, the function that does the actual testing, directly. Note that ismembc requires sorted arrays (so you can drop the sort if your input is sorted already!)

tic,a=sort(a);b=sort(b);a(ismembc(a,b)),toc
ans =
    76
   338
   490
   548
   550
   801
   914
   930
Elapsed time is 0.000473 seconds.

这篇关于一种更快的方法来实现intersect()给我什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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