# NumPy: numpy.asmatrix() function

## numpy.asmatrix() function

The numpy.asmatrix() function is used to interpret the input as a matrix.
Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).

Syntax:

`numpy.asmatrix(data, dtype=None)` Parameters:

Name Description Required /
Optional
data Input data. Required
dtype Data-type of the output matrix. optional

Return value:

mat : matrix
data interpreted as a matrix.

Example: Converting ndarray to matrix with asmatrix()

``````>>> import numpy as np
>>> x = np.array([[1,2], [3,4]])
>>> n = np.asmatrix(x)
>>> x[0,0] = 5
>>> n
matrix([[5, 2],
[3, 4]])
``````

The above code demonstrates the use of asmatrix() function to convert an ndarray to a matrix. Initially, an ndarray x with values [[1,2],[3,4]] is created. Using asmatrix() function, x is converted to a matrix n.
The two-dimensional matrix n is a view of the array x. Then the value of x[0,0] is changed to 5. Since both x and n share the same data buffer, the change in value of x is reflected in n. Therefore, n now becomes [[5,2],[3,4]].

Pictorial Presentation: Example-2: NumPy.asmatrix() function

``````>>> import numpy as np
>>> a = np.array([[2,3], [4,5]])
>>> x = np.asmatrix(a)
>>> a[0,0] = 5
>>> x
matrix([[5, 3],
[4, 5]])
``````

Pictorial Presentation: Python - NumPy Code Editor:

Previous: ascontiguousarray()
Next: copy()

﻿