NumPy matrix()

The matrix() method is used to create a matrix from a 2-D array-like object.

Example

import numpy as np

# create  2-D array
array1 = [[1, 2], [3, 4]]  

# use of matrix() to create matrix result = np.matrix(array1)
print(result) ''' Output: [[1 2] [3 4]] '''

matrix() Syntax

The syntax of matrix() is:

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

matrix() Arguments

The matrix() method takes the following arguments:

  • data - input data used to create the matrix
  • dtype (optional) - data type of the matrix
  • copy (optional) - determines whether a copy of data should be made or not

matrix() Return Value

The matrix() method returns a matrix object from an array-like object.


Example 1: Create a Matrix

import numpy as np

# create a list
array1 = [[1, 2, 3], 
                [4, 5, 6], 
                [7, 8, 9]] 

# use matrix() to create a matrix result = np.matrix(array1, dtype = int)
print(result)

Output

[[1 2 3]
 [4 5 6]
 [7 8 9]]

If unspecified, the default dtype is float.


Example 2: Use of copy Argument in matrix()

import numpy as np

# create a 2-D array
array1 = [[1, 2], [3, 4]] 
  
# create matrix with default copy=True 
matrix1 = np.matrix(array1)  

# modify the original data
array1[0][0] = 5

# create matrix with copy=False
matrix2 = np.matrix(array1, copy=False)  

print("Matrix with copy=True:")
print(matrix1)

print("Matrix with copy=False:")
print(matrix2)

Output

Matrix with copy=True:
[[1 2]
 [3 4]]
Matrix with copy=False:
[[5 2]
 [3 4]]

In the above example, when creating matrices using matrix() with copy=True, a copy of the data is made, resulting in a separate matrix.

With copy=False, the matrix shares the data with the original object. Modifying the original data affects the matrix.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community