|
a |
|
b/util/countmember.m |
|
|
1 |
function COUNT = countmember(A,B) |
|
|
2 |
% COUNTMEMBER - count members |
|
|
3 |
% |
|
|
4 |
% COUNT = COUNTMEMBER(A,B) counts the number of times the elements of array A are |
|
|
5 |
% present in array B, so that C(k) equals the number of occurences of |
|
|
6 |
% A(k) in B. A may contain non-unique elements. C will have the same size as A. |
|
|
7 |
% A and B should be of the same type, and can be cell array of strings. |
|
|
8 |
% |
|
|
9 |
% Examples: |
|
|
10 |
% countmember([1 2 1 3],[1 2 2 2 2]) |
|
|
11 |
% % -> 1 4 1 0 |
|
|
12 |
% countmember({'a','b','c'},{'a','x','a'}) |
|
|
13 |
% % -> 2 0 0 |
|
|
14 |
% |
|
|
15 |
% See also ISMEMBER, UNIQUE, HISTC |
|
|
16 |
|
|
|
17 |
% tested in R2015a |
|
|
18 |
% version 2.0 (apr 2016) |
|
|
19 |
% (c) Jos van der Geest |
|
|
20 |
% email: samelinoa@gmail.com |
|
|
21 |
|
|
|
22 |
% History: |
|
|
23 |
% 1.0 (2005) created |
|
|
24 |
% 1.1 (??): removed dum variable from [AU,dum,j] = unique(A(:)) to reduce |
|
|
25 |
% overhead |
|
|
26 |
% 1.2 (dec 2008) - added comments, fixed some spelling and grammar |
|
|
27 |
% mistakes, after being selected as Pick of the Week (dec 2008) |
|
|
28 |
% 2.0 (apr 2016) - updated for R2015a |
|
|
29 |
|
|
|
30 |
% input checks |
|
|
31 |
narginchk(2,2) ; |
|
|
32 |
if ~isequal(class(A), class(B)), |
|
|
33 |
error('Both inputs should be of the same class.') ; |
|
|
34 |
end |
|
|
35 |
|
|
|
36 |
if isempty(A) || isempty(B), |
|
|
37 |
% nothing to do |
|
|
38 |
COUNT = zeros(size(A)) ; |
|
|
39 |
else |
|
|
40 |
% which elements are unique in A, |
|
|
41 |
% also store the position to re-order later on |
|
|
42 |
[AUnique, ~, j] = unique(A(:)) ; |
|
|
43 |
% assign each element in B a number corresponding to the element of A |
|
|
44 |
[~, Loc] = ismember(B, AUnique) ; |
|
|
45 |
% count these numbers |
|
|
46 |
N = histc(Loc(:), 1:length(AUnique)) ; |
|
|
47 |
% re-order according to A, and reshape |
|
|
48 |
COUNT = reshape(N(j),size(A)) ; |
|
|
49 |
end |