Interpret the input as a matrix in Numpy


To Interpret the input as a matrix, use the numpy.asmatrix() method in Python Numpy. Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

Steps

At first, import the required library −

import numpy as np

Create a 2d array −

arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Arra −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

To Interpret the input as a matrix, use the numpy.asmatrix() method in Python Numpy −

res = np.asmatrix(arr)
print("
Result...
",res)

Set some values −

arr[0,2] = 99
arr[1,1] = 199
arr[2,1] = 299

Display the updated matrix −

print("
Updated Matrix...
",arr)

Example

import numpy as np

# Create a 2d array
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To Interpret the input as a matrix, use the numpy.asmatrix() method in Python Numpy res = np.asmatrix(arr) print("
Result...
",res) # Set some values arr[0,2] = 99 arr[1,1] = 199 arr[2,1] = 299 # Display the updated matrix print("
Updated Matrix...
",arr)

Output

Array...
[[36 36 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

Result...
[[36 36 78 88]
[92 81 98 45]
[22 67 54 69]
[69 80 80 99]]

Updated Matrix...
[[ 36 36 99 88]
[ 92 199 98 45]
[ 22 299 54 69]
[ 69 80 80 99]]

Updated on: 17-Feb-2022

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements