|
"Arthur Zheng" <hzheng7@gatech.edu> wrote in message <h4slnv$9dj$1@fred.mathworks.com>...
> there are two arrays, e.g.
> arr1 = [ 1 2 3 4 5 6];
> arr2 = [ 2 4 3];
>
> What is an efficient way to calculate the number of common numbers in the two arrays? Is there such a function? In the above example, the result should be 3, since the common numbers are: 2, 3, 4.
Nathan's "length(intersect(arr1, arr2))" fails, if elements are repeated:
intersect([1,2,3,4,5,6,2], [2,4,3])
=> [2, 3, 4]
For repetitions:
sum(ismember(arr1, arr2))
If efficient means high performance for small vectors (e.g. if called millions of times), you can avoid the offset of ISMEMBER:
sum(ismembc(sort(arr1), sort(arr2)))
For large arrays (> 100.000 elements) calling the MEX directly is not a big advantage. But if you know, the arrays are sorted already, you could save the time for sorting them again.
Good luck, Jan
|