Wednesday 27 January 2010

How to convert a matrix from a NxM to a X-Y-Z format

Somtimes a matrix need to be converted from the standard NxM format to a vector of X-Y-Z triplets (row-index, column-index, value).
Here you have a simple way to convert a 2D array in a X-Y-Z format in python:


from pylab import *

def mat2triplet(mat):

    rows = arange(mat.shape[0]*mat.shape[1])/mat.shape[1]
    # a vector of row indices

    cols = arange(mat.shape[0]*mat.shape[1])%mat.shape[1]
    # a vector of column indices

    values = mat.flatten()
    # a vector of values

    triplet = dstack((rows,cols,values))
    triplet = squeeze(triplet)

    return triplet


A matrix:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]


is converted into:
[[ 0  0  0]
 [ 0  1  1]
 [ 0  2  2]
 [ 1  0  3]
 [ 1  1  4]
 [ 1  2  5]
 [ 2  0  6]
 [ 2  1  7]
 [ 2  2  8]
 [ 3  0  9]
 [ 3  1 10]
 [ 3  2 11]]

1 comment: