Wednesday, January 16, 2013

Finding Vector frequency in a matrix

Imagine, I have a matrix where a some vector repeats itself many times within a matrix.We would like to count how many times does they occur?

A=[1 2 3; 0 0 0; 4 5 6; 0 0 0; 1 2 3; 3 4 5; 4 5 6; 9 9 9; 9 9 9; 0 0 0; 1 2 3];
Let's first make them row-wise unique(UniqueA) and capture the indexes of A by iA and indexes of UniqueA by iUniqueA


>> [UniqueA,iA,iUniqueA]=unique(A,'rows')
UniqueA =
     0     0     0
     1     2     3
     3     4     5
     4     5     6
     9     9     9

iA =
    10
    11
     6
     7
     9

iUniqueA =
     2
     1
     4
     1
     2
     3
     4
     5
     5
     1
     2

Now, using histogram count (histc command) over iUniqueA and edges (bins) as a series of numbers from 1 to numel(iA). Therefore,

>> count = histc(iUniqueA,1:numel(iA))

ans =

     3
     3
     1
     2
     2

Now we can see UniqueA and count side by side
UniqueA      count
0 0 0 3
1 2 3 3
3 4 5 1
4 5 6 2
9 9 9 2

Now we know how many times a vector has occured (vector's frequency) within a matrix.






No comments:

Post a Comment

Please ask if anything is not clear enough..........