# How do I divide the columns of a matrix by the sum of its elements?

I am trying to create a transition matrix for a network. In order to do this, I need to sum down the column (the out degree), and then divide the column by the out degree in order to normalize it.

I am able to sum down the column. What I am unable to figure out how to do efficiently and easily is to divide the column by the sum.

L = {{0, 1, 0, 1, 0, 0, 0},
{0, 0, 1, 1, 1, 0, 0},
{0, 1, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 0}};


If you need to do this with all columns, then:

Transpose[#/Total[#] & /@ Transpose[L]]

• Where can I learn how to write these one liners that are so powerful? I never seem to fully understand the notation. Commented Mar 29, 2013 at 2:29
• @user2200667 there is a tutorial collection Core Language - I'd start there. But also you can start by looking up in documentation symbols like /@ & # // etc. Commented Mar 29, 2013 at 2:42

You can use Normalize with its second argument for this purpose:

(mat = Normalize[#, Total] & /@ Transpose@L // Transpose) // MatrixForm


Instead, if you were normalizing the rows by the sum of their elements, you could simply leave out the transposes and do

mat = Normalize[#, Total] & /@ L


or even

mat = #/Tr@#& /@ L


For your specific problem (transition matrix), you can use the new Markov process related functions in version 9 to get the transition matrix:

With[{m = DiscreteMarkovProcess[, L]},
mat = MarkovProcessProperties[m, "TransitionMatrix"]
] // MatrixForm


Why transpose when you don't have to?

#/Total[L] & /@ L


(Just resurrecting this for a bit of "code golf.")

• The answer to my silly rhetorical question is: because it is faster. My "shorter" code results in longer computational time. The solution using Transpose will divide each row (which was, originally, a column) by a single value, List / Real. My answer divides each row by the list of column totals, List / List. At any large scale, this adds up to cost way more than 2x Transpose. There's a long comment for a short answer. Commented Jun 19, 2017 at 6:33