title: N-Dimensional Histogram Counts
body: <p>I am currently trying to code up a function to assign probabilities to a collection of vectors using a histogram count. This is essentially a counting exercise, but requires some finesse to be able to achieve efficiently. I will illustrate with an example:</p>
  
  <p>Say that I have a matrix <code>X = [x1, x2....xM]</code> with <code>N</code> rows and <code>M</code> columns. Here, <code>X</code> represents a collection of <code>M</code>, <code>N</code>-dimensional vectors. IN other words, each of the columns of <code>X</code> is an <code>N</code>-dimensional vector. </p>
  
  <p>As an example, we can generate such an <code>X</code> for <code>M = 10000</code> vectors and <code>N = 5</code> dimensions using:</p>
  
  <pre><code>X = randint(5,10000)
  </code></pre>
  
  <p>This will produce a 5 x 10000 matrix of 0s and 1s, where each column is represents a 5 dimensional vector of 1s and 0s.</p>
  
  <p>I would like to assign a probability to each of these vectors through a basic histogram count. The steps are simple: first find the unique columns of <code>X</code>; second, count the number of times each unique column occurs. The probability of a particular occurrence is then the #of times this column was in X / total number of columns in <code>X</code>.</p>
  
  <p>Returning to the example above, I can do the first step using the <code>unique</code> function in MATLAB as follows:</p>
  
  <pre><code>UniqueXs = unique(X','rows')' 
  </code></pre>
  
  <p>The code above will return <code>UniqueXs</code>, a matrix with <code>N</code> rows that only contains the unique columns of X. Note that the transposes are due to weird MATLAB input requirements.</p>
  
  <p>However, I am unable to find a good way to count the number of times each of the columns in UniqueX is in X. So I'm wondering if anyone has any suggestions?</p>
  
  <p>Broadly speaking, I can think of two ways of achieving the counting step. The first way would be to use the <code>find</code> function, though I think this may be slow since <code>find</code> is an elementwise operation. The second way would be to call <code>unique</code> recursively as it can also provide the index of <strong>one</strong> of the unique columns in <code>X</code>. This should allow us to remove that column from <code>X</code> and redo <code>unique</code> on the resulting <code>X</code> and keep counting.</p>
  
  <p>Ideally, I think that <code>unique</code> might already be doing some counting so the most efficient way would probably be to work without the built-in functions.</p>