I am finding that a lot of time spent in my matlab function is in this code:
intersect(freq_bins, our_bins);
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With