Matrices: Matrices in Python
Computing with matrices and vectors
You can easily add matrices in MATLAB, subtract then, multiply them (also scalar multiplication) and exponentiate them. Examples illustrate this best.
Computing with matrices and vectors
>>> import numpy as np
>>> A = np.array([[1, 2, 3], [4, 5, 6]]); print(A)
[[1 2 3]
[4 5 6]]
>>> B = np.diag([1,2,3]); print(B)
[[1 0 0]
[0 2 0]
[0 0 3]]
>> At = np.transpose(A); print(At) # transposed of A
[[1 4]
[2 5]
[3 6]]
>>> A.dot(B) # matrix multiplication as method
array([[ 1, 4, 9],
[ 4, 10, 18]])
>>> print( A @ B) # matrix multiplication as operator
[[ 1 4 9]
[ 4 10 18]]
>>> print(A @ At)
[[14 32]
[32 77]]
>>> C = At @ A; print(C)
[[17 22 27]
[22 29 36]
[27 36 45]]
>>> print(C + B) # addition of matrices
[[18 22 27]
[22 31 36]
[27 36 48]]
>>> print(3*A) # scalar multiplication
[[ 3 6 9]
[12 15 18]]
>>> v = np.array([[1],[2],[3]]); print(v)
[[1]
[2]
[3]]
>>> print(A @ v) # matrix-vector multiplication
[[14]
[32]]
>>> print(vt @ At) # vector-matrix multiplication
[[14]
[[14 32]]
>>>
>>> import numpy.linalg as la
>>> Bmat = matrix(B) # change from array to matrix datastructure
>>> la.matrix_power(Bmat, 3) # exponentiation: B^3 = B @ B @ B
matrix([[ 1, 0, 0],
[ 0, 8, 0],
[ 0, 0, 27]])
>>> la.matrix_power(Bmat, -1) # inverse as power
matrix([[1. , 0. , 0. ],
[0. , 0.5 , 0. ],
[0. , 0. , 0.33333333]])
>>> la.inv(B) # inverse array
array([[1. , 0. , 0. ],
[0. , 0.5 , 0. ],
[0. , 0. , 0.33333333]])
If you want to use addition, subtraction, multiplication and exponentiation in components of vector or matrix elements, you can do so too. We give some examples.
Operations on matrix elements
>>> print(A)
[[1 2 3]
[4 5 6]]
>>> print(A**2)
[[ 1 4 9]
[16 25 36]]
>>> print(A*A)
[[ 1 4 9]
[16 25 36]]
>>> print(A / A)
[[1. 1. 1.]
[1. 1. 1.]]
Unlock full access