Build a block matrix from a list with depth one in Numpy


To build a block of matrix, use the numpy.block() method in Python Numpy. Here, we will build from list with depth one. . Blocks in the innermost lists are concatenated along the last dimension (-1), then these are concatenated along the second-last 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.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

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, arr2, 99]))

Example

import numpy as np

# Creating two numpy arrays using the array() method
# We have inserted elements of int type
arr1 = np.array([49, 76, 61, 82, 69, 29])
arr2 = np.array([40, 60, 89, 55, 32, 98])

# 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, arr2, 99]))

Output

Array 1...
[49 76 61 82 69 29]

Array 2...
[40 60 89 55 32 98]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(6,)

Our Array 2 Shape...
(6,)

Result...
[49 76 61 82 69 29 40 60 89 55 32 98 99]

Updated on: 18-Feb-2022

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements