Reputation: 2989
I have four numpy arrays like:
X1 = array([[1, 2], [2, 0]])
X2 = array([[3, 1], [2, 2]])
I1 = array([[1], [1]])
I2 = array([[1], [1]])
And I'm doing:
Y = array([I1, X1],
[I2, X2]])
To get:
Y = array([[ 1, 1, 2],
[ 1, 2, 0],
[-1, -3, -1],
[-1, -2, -2]])
Like this example, I have large matrices, where X1
and X2
are n x d
matrices.
Is there an efficient way in Python whereby I can get the matrix Y
?
Although I am aware of the iterative manner, I am searching for an efficient manner to accomplish the above mentioned.
Here, Y
is an n x (d+1)
matrix and I1
and I2
are identity matrices of the dimension n x 1
.
Upvotes: 3
Views: 533
Reputation: 12486
For a numpy
array
, this page suggests the syntax may be of the form
vstack([hstack([a,b]),
hstack([c,d])])
Upvotes: 0
Reputation: 68692
How about the following:
In [1]: import numpy as np
In [2]: X1 = np.array([[1,2],[2,0]])
In [3]: X2 = np.array([[3,1],[2,2]])
In [4]: I1 = np.array([[1],[1]])
In [5]: I2 = np.array([[4],[4]])
In [7]: Y = np.vstack((np.hstack((I1,X1)),np.hstack((I2,X2))))
In [8]: Y
Out[8]:
array([[1, 1, 2],
[1, 2, 0],
[4, 3, 1],
[4, 2, 2]])
Alternatively you could create an empty array of the appropriate size and fill it using the appropriate slices. This would avoid making intermediate arrays.
Upvotes: 3
Reputation: 8153
You need numpy.bmat
In [4]: A = np.mat('1 ; 1 ')
In [5]: B = np.mat('2 2; 2 2')
In [6]: C = np.mat('3 ; 5')
In [7]: D = np.mat('7 8; 9 0')
In [8]: np.bmat([[A,B],[C,D]])
Out[8]:
matrix([[1, 2, 2],
[1, 2, 2],
[3, 7, 8],
[5, 9, 0]])
Upvotes: 2