title: What is the fastest way to count elements in an array?
body: <p>In my models, one of the most repeated tasks to be done is counting the number of each element within an array. The counting is from a closed set, so I know there are <code>X</code> types of elements, and all or some of them populate the array, along with zeros that represent 'empty' cells. The array is not sorted in any way, and could by quite long (about 1M elements), and this task is done thousands of times during one simulation (which is also part of hundreds of simulations). The result should be a vector <code>r</code> of size <code>X</code>, so <code>r(k)</code> is the amount of <code>k</code> in the array.</p>
  
  <h3>Example:</h3>
  
  <p>For <code>X = 9</code>, if I have the following input vector:</p>
  
  <pre><code>v = [0 7 8 3 0 4 4 5 3 4 4 8 3 0 6 8 5 5 0 3]
  </code></pre>
  
  <p>I would like to get this result:</p>
  
  <pre><code>r = [0 0 4 4 3 1 1 3 0]
  </code></pre>
  
  <p>Note that I don't want the count of zeros, and that elements that don't appear in the array (like <code>2</code>) have a <code>0</code> in the corresponding position of the result vector (<code>r(2) == 0</code>).</p>
  
  <p>What would be the <strong>fastest</strong> way to achieve this goal?</p>