title: Numpy matrix row comparison
body: <p>The question is more focused on performance of calculation.</p>
  
  <p>I have 2 matrix with the same number of columns and different number of rows. One matrix is the 'pattern' whose rows have to be compared separately with the other matrix rows (all rows), then to be able to extract statistical values of mean equal to pattern, std,...
  So, I have the following matrix and the computation is the following one:</p>
  
  <pre><code>numCols = 10
  pattern = np.random.randint(0,2,size=(7,numCols))
  matrix = np.random.randint(0,2,size=(5,numCols))
  
  comp_mean = np.zeros(pattern.shape[0])
  for i in range(pattern.shape[0]):
      comp_mean[i] = np.mean(np.sum(pattern[i,:] == matrix, axis=1))
  
  print comp_mean # Output example: [ 1.6  1.   1.6  2.2  2.   2.   1.6]
  </code></pre>
  
  <p>This is clear. The problem is that the number of matrix rows of both is much bigger (~1.000.000). So this code goes very slow. I tryed to implement numpy syntaxis as sometimes it surprises me improving the calculation time. So I did the following code (it could be strange, but it works!):</p>
  
  <pre><code>comp_mean = np.mean( np.sum( (pattern[np.repeat(np.arange(pattern.shape[0]), matrix.shape[0])].ravel() == np.tile(matrix.ravel(),pattern.shape[0])).reshape(pattern.shape[0],matrix.shape[0],matrix.shape[1]), axis=2 ),axis=1)
  print comp_mean
  </code></pre>
  
  <p>However, this code is slower than the previous one where the 'for' bucle is used. So I would like to know if there is any possibility to speed up the calculation.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have checked the runtime of the different approaches for the real matrix and the result is the following:</p>
  
  <ul>
  <li>Me - Approach 1:  <strong>18.04</strong> seconds</li>
  <li>Me - Approach 2:  <strong>303.10</strong> seconds</li>
  <li>Divakar - Approach 1:  <strong>18.79</strong> seconds</li>
  <li>Divakar - Approach 2:  <strong>65.11</strong> seconds</li>
  <li>Divakar - Approach 3.1:  <strong>137.78</strong> seconds</li>
  <li>Divakar - Approach 3.2:  <strong>59.59</strong> seconds</li>
  <li>Divakar - Approach 4:  <strong>6.06</strong> seconds</li>
  </ul>
  
  <p><strong>EDIT(2)</strong></p>
  
  <p>Previous runs where performed in a laptop. I have run the code on a desktop. I have avoided the worst results, and the new runtimes are now different:</p>
  
  <ul>
  <li>Me - Approach 1:  <strong>6.25</strong> seconds</li>
  <li>Divakar - Approach 1:  <strong>4.01</strong> seconds</li>
  <li>Divakar - Approach 2:  <strong>3.66</strong> seconds</li>
  <li>Divakar - Approach 4:  <strong>3.12</strong> seconds</li>
  </ul>