# 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([, ])

I2 = array([, ])
```

```

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

You need numpy.bmat

``````In : A = np.mat('1 ; 1 ')
In : B = np.mat('2 2; 2 2')
In : C = np.mat('3 ; 5')
In : D = np.mat('7 8; 9 0')
In : np.bmat([[A,B],[C,D]])
Out:
matrix([[1, 2, 2],
[1, 2, 2],
[3, 7, 8],
[5, 9, 0]])
```

```
+2

source

``````In : import numpy as np

In : X1 = np.array([[1,2],[2,0]])

In : X2 = np.array([[3,1],[2,2]])

In : I1 = np.array([,])

In : I2 = np.array([,])

In : Y = np.vstack((np.hstack((I1,X1)),np.hstack((I2,X2))))

In : Y
Out:
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`

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

```
0

source

All Articles