NumPy | asmatrix method
Start your free 7-days trial now!
NumPy's asmatrix(~) method constructs a matrix from a sequence of data (e.g. arrays and tuples).
Parameters
1. a | array-like
The sequence of data used to construct a matrix.
If a is a NumPy array or matrix, no copying would be done - modifying the result of asmatrix(~) would also automatically modify a.
2. dtype | string or type | optional
Type of data stored in the NumPy array. By default, the type will be inferred.
Return value
A NumPy matrix.
Examples
Basic usage
To create a 2 by 2 matrix:
np.asmatrix([[4,5],[6,7]])
matrix([[4, 5], [6, 7]])
Case when array is not copied
Suppose we create a NumPy matrix out of a NumPy array, like so:
b = np.asmatrix(a)
When we modify the contents of b:
b[0,0] = 9b
matrix([[9, 5], [6, 7]])
This would automatically modify a as well:
a
array([[9, 5], [6, 7]])
What's happening here is that the NumPy objects a and b actually share the same memory space, so modifying one would involve modifying the other. Note that this happens only if we try to call asmatrix(~) on a NumPy array or matrix.