numpy.matrix() in Python


The Python numpy.matrix() function returns a matrix from the string of data of array-like object. The returned matrix is a specialized 2D array.

Basic Syntax

Following is the basic syntax for numpy.matrix() function in Python:

numpy.matrix(data, dtype = None)

And the parameters are:

Parameter Description
data Data needs to be array-like or String.
dtype Returned type data type.

Return Value

This function returns 2D specialized array from a string of data or array-like object.

Example

Following are the examples:

Example 1

#  numpy.matrix() example 

import numpy as np 

# string like input 
first = np.matrix('1 2; 3 4; 5,6') 
print("String like input : \n", first, "\n") 

# array like input 
second = np.matrix([[1, 2, 3], [7, 8]]) 
print("Array like input : \n", second) 

The output for the above program is as given below:

String like input :
[[1, 2],
[3, 4],
[5, 6]]
Array like input :
[[[1, 2, 3],
[7, 8]]]

Example 2

#  numpy.matrix() example 

import numpy as np 

# array like input 
a = np.matrix([[10, 20, 30, 40], [50, 60, 70, 80]]) 
print("Array like input : \n", a) 

The output for the above program is as given below:

Array like input :
[[[10, 20, 30, 40],
[50, 60, 70, 80]]]