What is the asmatrix() function from numpy in Python?

Overview

The asmatrix() function in Python is used to interpret input data as a matrix.

Syntax

asmatrix(data, dtype=None)

Parameter value

The asmatrix() function takes the following parameter values:

  • data: This represents the input data.
  • dtype: This represents the data type of the desired matrix.

Return value

The asmatrix() function returns data interpreted as a matrix.

Code example

from numpy import asmatrix, array
# creating an array
my_array = array([[1, 2], [3, 4]])
# interpreting the array as a matrix
my_matrix = asmatrix(my_array)
print(my_matrix)

Code explanation

  • Line 1: We import the array and asmatrix from numpy module.
  • Line 4: Using the array() function, we create a 2D array with 2 elements in each of the two arrays. The output is assigned to a variable my_array.
  • Line 7: Using the as_matrix() function, we interpreted the input data in my_array as a matrix and assigned the output to another variable, my_matrix.
  • Line 9: We print the my_matrix variable.

Free Resources