title: Scala: count entries from a list in a matrix
body: <p>I first need to say that I am quite new to Scala's collections' map reduce kind of functions.</p>
  
  <p>What I am trying to do is counting for each row of a matrix, how many times (all) the elements of a list (in this case numbers from 0 to n) appear. The ideal output would be a matrix with the same number of rows of the input matrix and as many columns as the length of the list.
  For example:</p>
  
  <pre><code>val list = List(0,1,2)
  
  val matrix = Array(
       Array(0,1,2,2),
       Array(0,0,1,0),
       Array(2,0,2,0))
  </code></pre>
  
  <p>in this case I would like to obtain such a matrix</p>
  
  <pre><code>1 1 2
  3 1 0
  2 0 2
  </code></pre>
  
  <p>What I came up with so far is the following:</p>
  
  <pre><code>val counts = matrix.map(r =&gt; r.map(x =&gt; (x,r.count(_ == x))).groupBy(_._1))
  </code></pre>
  
  <p>where the first part (up to groupBy) gives, for each row, couples of the kind (element, count). Then I tried to group this, but it doesn't quite work as I expected.</p>
  
  <p>This is of course very far away from what I'd like to achieve,as it just counts the elements in the matrix (so would never give a 0).</p>
  
  <p>Also, being in topic, is Array[Array[Type]] the best practice for dealing with matrices in Scala (given that no linear algebra should be applied, but rather counts and reading)?</p>
  
  <p>Thank you.</p>
  
  <p>EDIT:
  By rows was solved, but what if the same needs to be done on the columns? I guess transpose should be avoided if the matrix is very large.</p>