ベクトルの繰り返しでmatrixをつくる
一次元のarrayの繰り返しでmatrixを作る機会はそれなりに多い。Matlabではonesとのクロネッカー積を使っていたが、pythonでは代わりにrepeatとtileを使っている。
a=np.arange(3) a Out[0]: array([0, 1, 2])
列ベクトルとみなして行方向に繰り返すなら、repeat+reshapeか、tile+reshape+transpose。
a.repeat(2).reshape([3,2]) Out[1]: array([[0, 0], [1, 1], [2, 2]]) np.tile(a,2).reshape([2,3]).T Out[2]: array([[0, 0], [1, 1], [2, 2]])
行ベクトルとみなして列方向に繰り返す時は逆に、repeatの方にtransposeが必要。
np.tile(a,4).reshape([4,3]) Out[3]: array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]) a.repeat(4).reshape([3,4]).T Out[4]: array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]])