How to efficiently get the matrix of the desired shape in Python?

I have four numpy arrays, for example:

X1 = array([[1, 2], [2, 0]])

X2 = array([[3, 1], [2, 2]])

I1 = array([[1], [1]])

I2 = array([[1], [1]])

      

And I do:

Y = array([I1, X1],
          [I2, X2]])

      

To obtain:

Y = array([[ 1,  1,  2],
           [ 1,  2,  0],
           [-1, -3, -1],
           [-1, -2, -2]])

      

As in this example, I have large matrices where X1

u X2

are n x d

matrices.

Is there an efficient way in Python that I can get a matrix Y

?

Although I know the iterative manner, I am looking for an efficient way to accomplish the above.

Here Y

is a matrix n x (d+1)

, and I1

and I2

are identical dimension matrices n x 1

.

+3


source to share


3 answers


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]])

      

+2


source


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 can create an empty array of the appropriate size and fill it with the appropriate fragments. This will avoid intermediate arrays.

+3


source


For numpy

array

this page, it assumes that the syntax might be

vstack([hstack([a,b]),
        hstack([c,d])])

      

0


source







All Articles