Build a block matrix in Numpy

NumpyServer Side ProgrammingProgramming

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...\n", arr1)
print("\nArray 2...\n", arr2)

Get the type of the arrays −

print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

Get the dimensions of the Arrays −

print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

Get the shape of the Arrays −

print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

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

print("\nResult...\n",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...\n", arr1)
print("\nArray 2...\n", arr2)

# Get the type of the arrays
print("\nOur Array 1 type...\n", arr1.dtype)
print("\nOur Array 2 type...\n", arr2.dtype)

# Get the dimensions of the Arrays
print("\nOur Array 1 Dimensions...\n",arr1.ndim)
print("\nOur Array 2 Dimensions...\n",arr2.ndim)

# Get the shape of the Arrays
print("\nOur Array 1 Shape...\n",arr1.shape)
print("\nOur Array 2 Shape...\n",arr2.shape)

# To build a block of matrix, use the numpy.block() method in Python Numpy
print("\nResult...\n",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.]]
raja
Updated on 17-Feb-2022 10:29:19

Advertisements