6
$\begingroup$

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}};
$\endgroup$
0

3 Answers 3

10
$\begingroup$

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

Transpose[#/Total[#] & /@ Transpose[L]]
$\endgroup$
2
  • $\begingroup$ Where can I learn how to write these one liners that are so powerful? I never seem to fully understand the notation. $\endgroup$
    – olliepower
    Commented Mar 29, 2013 at 2:29
  • $\begingroup$ @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. $\endgroup$ Commented Mar 29, 2013 at 2:42
12
$\begingroup$

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
$\endgroup$
0
4
$\begingroup$

Why transpose when you don't have to?

#/Total[L] & /@ L

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

$\endgroup$
1
  • 3
    $\begingroup$ 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. $\endgroup$ Commented Jun 19, 2017 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.