I am looking for a way to efficiently stack a the same row to several stacked 2D matrices.
Concretely, I am interested in stacking matrices of shape (3,4) which have float elements. For example, if there were 2 matrices to be stacked:
import numpy as np
np.arange(24.).reshape(2,3,4)
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
[16., 17., 18., 19.],
[20., 21., 22., 23.]]])
and having a row of shape (1,1,4) to be stacked:
row = np.array([[[101.,102.,103.,104.]]])
The final result would look like this (stacked (4,4) matrices):
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[101., 102., 103., 104.]],
[[ 12., 13., 14., 15.],
[ 16., 17., 18., 19.],
[ 20., 21., 22., 23.],
[101., 102., 103., 104.]]])
Until know, the best attempt that I did is by using np.tile:
import numpy as np
M_stacked = np.arange(24.).reshape(2,3,4)
row = np.array([[[101.,102.,103.,104.]]])
np.concatenate((M_stacked, np.tile(row, (len(M_stacked),1,1))), axis=1)
But I believe this may not be the most efficient solution, specially when the number of stacked matrices increases. Is there a better approach?
Thanks in advance!
As a reference, these are the timings that I am getting:
If there are 2 stacked matrices:
M_stacked = np.arange(2.*3.*4.).reshape(2,3,4)
%timeit np.concatenate((M_stacked, np.tile(row, (len(M_stacked),1,1))), axis=1)
7.2 µs ± 85 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each))
If there are 1000 stacked matrices:
M_stacked = np.arange(1000.*3.*4.).reshape(1000,3,4)
%timeit np.concatenate((M_stacked, np.tile(row, (len(M_stacked),1,1))), axis=1)
28.8 µs ± 108 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)