Skip to content

Instantly share code, notes, and snippets.

@ccorcos
Created April 22, 2014 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccorcos/11198159 to your computer and use it in GitHub Desktop.
Save ccorcos/11198159 to your computer and use it in GitHub Desktop.
Python NumPy: this function takes a list of matrices and converts it into a 2D matrix filling in zeros where no matrix is specified
from pylab import *
from pprint import pprint
def arrayToList(arr):
if type(arr) == type(array([])):
return arrayToList(arr.tolist())
elif type(arr) == type([]):
return [arrayToList(a) for a in arr]
else:
return arr
def prettyArray(arr):
pprint(arrayToList(arr))
def emptyList(shape):
arr = zeros(shape)
return arr.tolist()
A = emptyList([3, 3])
A[0][0] = ones([3, 3])
A[2][0] = ones([2, 3])
A[0][1] = ones([3, 1])
A[1][2] = ones([5, 5])
A = arrayToList(A)
prettyArray(A)
def flattenMatrix(A):
"""
Given a sparse (or dense) list of matricies, this function
will flatten this matrix into a 2D matrix filling in zeros
where no matrices are specified
"""
rows, cols = array(A).shape
rowSizes = [0] * rows
colSizes = [0] * cols
for i in range(len(A)):
for j in range(len(A[i])):
elem = A[i][j]
if type(elem) == type([]) or type(elem) == type(array([])):
r, c = array(elem).shape
if rowSizes[i] != 0 and rowSizes[i] != r:
print "ERROR: inconsisten row sizes"
else:
rowSizes[i] = r
if colSizes[j] != 0 and colSizes[j] != c:
print "ERROR: inconsisten col sizes"
else:
colSizes[j] = c
rowIndexes = [0] + add.accumulate(rowSizes).tolist()
colIndexes = [0] + add.accumulate(colSizes).tolist()
B = zeros([sum(rowSizes), sum(colSizes)])
for i in range(len(A)):
for j in range(len(A[i])):
rowStart = rowIndexes[i]
rowEnd = rowIndexes[i + 1]
colStart = colIndexes[j]
colEnd = colIndexes[j + 1]
B[rowStart:rowEnd, colStart:colEnd] = array(A[i][j])
return B
A = flattenMatrix(A)
prettyArray(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment