numpy.matrix Method in Python



The numpy.matrix method is used to interpret a given input as a matrix. It returns a matrix from an array-like object. Its syntax is as follows −

numpy.matrix(data, dtype=None, copy=bool)

where,

  • data - It is the input data.

  • dtype - It represents the data type of the output matrix.

  • copy - If the input data is already an ndarray, then this flag copy determines whether the data is to be copied (default behavior), or whether a view is to be constructed.

Example 1

Let us consider the following example −

# import numpy library
import numpy as np

# matrix function
y = np.matrix([[4, 5], [7, 8]])
print("Matrix Elements: 
", y)

Output

It will generate the following output −

Matrix Elements:
[[4 5]
[7 8]]

Example 2

Let us take another example −

# import numpy library
import numpy as np

# matrix function
b = np.matrix([[78, 79, 80.23], [2, 4.5, 6]], dtype=int)
print("Matrix Elements: 
", b)

Output

It will generate the following output −

Matrix Elements:
[[78 79 80]
[ 2 4 6]]

Here, observe that we have dtype=int, hence it converts the float values to integer in the output matrix.


Advertisements