Created
April 22, 2014 23:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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