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

Question:

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.

Asked By: Jannat Arora

||

Answers:

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.

Answered By: JoshAdel

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]])
Answered By: Chris Kuklewicz

For a numpy array, this page suggests the syntax may be of the form

vstack([hstack([a,b]),
        hstack([c,d])])
Answered By: Li-aung Yip
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.