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 arraymy_array = array([[1, 2], [3, 4]])# interpreting the array as a matrixmy_matrix = asmatrix(my_array)print(my_matrix)
Code explanation
- Line 1: We import the
arrayandasmatrixfromnumpymodule. - Line 4: Using the
array()function, we create a2Darray with2elements in each of the two arrays. The output is assigned to a variablemy_array. - Line 7: Using the
as_matrix()function, we interpreted the input data inmy_arrayas a matrix and assigned the output to another variable,my_matrix. - Line 9: We print the
my_matrixvariable.