# Map a matrix to a block matrix

Hello,

I have a function that maps an element $x$ into a $1\times n$ matrix, say for example $[x,x,x]$. I would like to map this function to a matrix and consider the resulting matrix as a "block matrix". E.g: change matrix([[1,2],[3,4]]) into matrix([[1,1,1,2,2,2],[3,3,3,4,4,4]]).

For now, I use a trick that basically converts back the matrix to a a list using something like:

block_matrix([[f(elt) for elt in row] for row in M.rows()])


but it looks quite dirty so I would like to know if there are some better way to proceed.

Thank you!

edit retag close merge delete

2

I think your solution is not dirty at all. This is very much what I would do.

Sort by » oldest newest most voted

Here's another way to do it:

def f(elt):
return matrix([elt for j in range(3)])

block_matrix([map(f,row) for row in M])


However, from testing with %%timeit on random 3x3 matrices (random_matrix(RDF,3,3)) it seems that this is always very slightly slower than your list constructor approach:

1000 loops, best of 3: 932 µs per loop


my above approach:

1000 loops, best of 3: 958 µs per loop


I also tried using M.apply_map(f) but it seems that that function assumes that f returns a scalar element and I couldn't get it to work.

more