short question - is this the FASTEST way to create a 16x16 (or also nxn) matrix with zeros in python & numpy?
a = np.matrix(np.zeros((16, 16), dtype = np.int))
The best way to speed up the creation of this matrix would be to skip using the matrix class entirely and just use np.zeros:
a = np.zeros((16, 16))
Skipping the use of matrix gives a 10x speedup:
%%timeit
a = np.matrix(np.zeros((16, 16)))
4.95 µs ± 50.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
a = np.zeros((16, 16))
495 ns ± 2.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
numpy.matrix has been deprecated:
Note It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
Edit: There's a nice discussion about the reasons behind matrix's deprecation that Paul Panzer linked to in the comments.
A common reason why people use matrix instead of array is so that a * b will perform matrix multiplication (instead of pairwise multiplication, like it will for standard array's). However, you can now use the shiny new matrix multiplication operator @ to easily perform matrix multiplication using standard arrays:
a = np.arange(2*2).reshape(2,2)
b = np.arange(2*2, 2*2*2).reshape(2,2)
print('a\n%s\n' % a)
print('b\n%s\n' % b)
print('a * b (pairwise multiplication)\n%s\n' % (a * b))
print('a @ b (matrix multiplication)\n%s\n' % (a @ b))
Output:
a
[[0 1]
[2 3]]
b
[[4 5]
[6 7]]
a * b (pairwise multiplication)
[[ 0 5]
[12 21]]
a @ b (matrix multiplication)
[[ 6 7]
[26 31]]
v as a column vector during the multiplication operation, but will still return the result as a normal 1D array.matmul docs (matmul is used to implement the behavior of the @ operator) for complete details.
np.matrixinstead ofnp.ndarray?