Build a block matrix in Numpy


To build a block of matrix, use the numpy.block() method in Python Numpy. Blocks in the innermost lists are concatenated along the last dimension (-1), then these are concatenated along the secondlast dimension (-2), and so on until the outermost list is reached.

Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working with scalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1.

Steps

At first, import the required library −

import numpy as np

Creating two numpy arrays using the array() method. We have inserted elements of int type −

arr1 = np.eye(2) * 2
arr2 = np.eye(3) * 2

Display the arrays −

print("Array 1...
", arr1) print("
Array 2...
", arr2)

Get the type of the arrays −

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

Get the dimensions of the Arrays −

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

Get the shape of the Arrays −

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

To build a block of matrix, use the numpy.block() method in Python Numpy −

print("
Result...
",np.block([[arr1,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))

Example

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.eye(2) * 2
arr2 = np.eye(3) * 2

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To build a block of matrix, use the numpy.block() method in Python Numpy print("
Result...
",np.block([[arr1,np.zeros((2, 3))], [np.ones((3, 2)), arr2]]))

Output

Array 1...
[[2. 0.]
[0. 2.]]

Array 2...
[[2. 0. 0.]
[0. 2. 0.]
[0. 0. 2.]]

Our Array 1 type...
float64

Our Array 2 type...
float64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 2)

Our Array 2 Shape...
(3, 3)

Result...
[[2. 0. 0. 0. 0.]
[0. 2. 0. 0. 0.]
[1. 1. 2. 0. 0.]
[1. 1. 0. 2. 0.]
[1. 1. 0. 0. 2.]]

Updated on: 17-Feb-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements