title: R - Divide each value in matrix by maximum value of its row/column
body: <p>I'm trying to transform the values in a matrix by dividing each value by the lesser of the maximum values of its column or row name.  I am having trouble because I don't know how to query the row/column for a particular value from inside a larger function.</p>
  
  <p>A small cut of the data looks like this: a weighted (symmetrical) adjacency matrix, mat: </p>
  
  <pre><code>              Acousmatic Acoustic Afro-beat Alternative Ambient
    Acousmatic         125       11         3           3       1
    Acoustic            11   112398      1810       24216    3824
    Afro-beat            3     1810     10386        1220     298
    Alternative          3    24216      1220      103286    2838
    Ambient              1     3824       298        2838   20400
  </code></pre>
  
  <p>As an example, I want to transform the value of "Alternative-Acoustic" (24216) by finding the maximum value for "Acoustic" given by its diagonal (112398) and the maximum value for "Alternative" given by its diagonal (103286), and by dividing "Alternative-Acoustic" (24216) by the lesser of those two numbers.  So in this case, the lesser would be "Alternative,"  so I want to transform the "Alternative-Acoustic" value with 24216/103286=~.2345.</p>
  
  <p>I want to automatically perform this transformation for all values in this matrix, which would result in a matrix with values ranging from 0-1 with the diagonals as all 1's.</p>
  
  <p>I tried the following in many different iterations with "mat" as both a matrix and a data frame, but I do not know how to correctly query the row and column maximums for each value in the matrix.  This is using nonexistent functions ('colmax' and 'rowmax'), but I think it most clearly expresses what I want to do:</p>
  
  <blockquote>
    <p>transformedmat &lt;- apply(mat,1:2, function(x) x/min(colmax(x),rowmax(x)))</p>
  </blockquote>
  
  <p>I also tried to write an embedded function, but that ended poorly, and I'm wondering if there's a simpler solution:</p>
  
  <pre><code>rescalemat &lt;- function(mat){
      apply(mat, 1, function(x){
      colmax&lt;-apply(mat, 2, function(x) max(x))
      rowmax&lt;-apply(mat, 1, function(x) max(x))
      x/min(colmax,rowmax)
      mat
  })
  }
  </code></pre>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Thanks.</p>