Ask Your Question
1

Map a matrix to a block matrix

asked 2018-04-11 00:15:48 +0200

tobiasBora gravatar image

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 flag offensive close merge delete

Comments

2

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

slelievre gravatar imageslelievre ( 2018-04-11 11:25:30 +0200 )edit

1 Answer

Sort by » oldest newest most voted
1

answered 2018-04-11 11:36:45 +0200

j.c. gravatar image

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:

your 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.

edit flag offensive delete link more

Comments

Ok, thank you for your help !

tobiasBora gravatar imagetobiasBora ( 2018-04-16 09:46:37 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-04-11 00:15:48 +0200

Seen: 468 times

Last updated: Apr 11 '18