COUNT_MATRIX_ELEMS

by

 

Obtains unique row elements from MxN matrix A and counts the number of occurrences.

count_matrix_elems.m
function [UN, C] = count_matrix_elems(A)
% COUNT_MATRIX_ELEMS - Obtains unique row elements from MxN matrix A and 
% counts the number of occurrences. 
% UN contains all matrix A distinct elements. 
% C will have the same size as UN. UN(k) has C(k) occurrences in matrix A.
%
%   Example:
% 
%       A = [1 2 3; 4 5 6; 1 2 3; 4 5 7; 1 2 1; 1 2 3; 4 5 6]
%       [UN, C] = count_matrix_elems(A)
%
% A =
% 
%      1     2     3
%      4     5     6
%      1     2     3
%      4     5     7
%      1     2     1
%      1     2     3
%      4     5     6
%      
% UN =
%      1     2     1
%      1     2     3
%      4     5     6
%      4     5     7
%  
% C =
%      1
%      3
%      2
%      1
% 
%   See also UNIQUE, FIND, NUMEL

% version 1.0 (October 2012)
% (c) Paulo Jorge Simes Coelho
% email: paulo.coelho@ipleiria.pt


% Check consistency in input arguments
error(nargchk(1,1,nargin)) ;
if isempty(A)
    UN = [] ;
    C = [] ;
    return
end
   
% Checks for unique elements in matrix A.
[UN, i, j] = unique(A,'rows');

% Count occurrences
C = zeros(length(UN),1); % Pre-allocating memory for speeding
for a = 1:length(UN)
    C(a) = numel(find(j == a));
end

Contact us