Duplicate entries in a matrix

Robert Kern robert.kern at gmail.com
Thu Jan 19 19:17:04 CET 2006


Chris Lasher wrote:
> Hello Pythonistas!
>   I'm looking for a way to duplicate entries in a symmetrical matrix
> that's composed of genetic distances. For example, suppose I have a
> matrix like the following:
> 
>   A        B        C
> A 0.000000 0.500000 1.000000
> B 0.500000 0.000000 0.500000
> C 1.000000 0.500000 0.000000
> 
> Say I want to duplicate entry B; the resulting matrix would look like:
> 
>   A        B        B        C
> A 0.000000 0.500000 0.500000 1.000000
> B 0.500000 0.000000 0.000000 0.500000
> B 0.500000 0.000000 0.000000 0.500000
> C 1.000000 0.500000 0.500000 0.000000

In [1]: from numpy import *

In [2]: A = array([[0.0, 0.5, 1.0],
   ...:            [0.5, 0.0, 0.5],
   ...:            [1.0, 0.5, 0.0]])

In [3]: B = repeat(A, [1,2,1])

In [4]: B
Out[4]:
array([[ 0. ,  0.5,  1. ],
       [ 0.5,  0. ,  0.5],
       [ 0.5,  0. ,  0.5],
       [ 1. ,  0.5,  0. ]])

In [5]: C = repeat(B, [1,2,1], axis=-1)

In [6]: C
Out[6]:
array([[ 0. ,  0.5,  0.5,  1. ],
       [ 0.5,  0. ,  0. ,  0.5],
       [ 0.5,  0. ,  0. ,  0.5],
       [ 1. ,  0.5,  0.5,  0. ]])

-- 
Robert Kern
robert.kern at gmail.com

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list