Importing and Using NumPy
NumPy provides essential matrix operations. To use its functions, import the library as follows:
import numpy as np # Standard import with np prefix
from numpy import * # Alternative import for direct access
Creating Matrices
Create matrices from one or two-dimensional data:
>>> import numpy as np
>>> vec = np.array([4, 5, 6])
>>> mat_from_vec = np.matrix(vec)
>>> print(mat_from_vec)
matrix([[4, 5, 6]])
>>> print(mat_from_vec.shape)
(1, 3)
Common matrix creation methods:
>>> zero_mat = np.mat(np.zeros((2, 3))) # 2x3 zero matrix
>>> ones_mat = np.mat(np.ones((3, 2), dtype=int)) # 3x2 integer ones
>>> rand_mat = np.mat(np.random.rand(3, 3)) # 3x3 random matrix
>>> diag_mat = np.mat(np.diag([7, 8, 9])) # Diagonal matrix
Common Matrix Operations
Matrix Multiplication
>>> A = np.mat([2, 3])
>>> B = np.mat([[4], [5]])
>>> C = A * B
>>> print(C)
matrix([[23]])
Element-wise Multiplication
>>> X = np.mat([3, 4])
>>> Y = np.mat([5, 6])
>>> Z = np.multiply(X, Y)
>>> print(Z)
matrix([[15, 24]])
Matrix Inversion and Transposition
>>> M = np.mat([[2, 0], [0, 2]])
>>> M_inv = M.I # Inverse
>>> M_trans = M.T # Transpose
Matrix Statistics
>>> data = np.mat([[1, 2], [3, 4], [5, 6]])
>>> col_sum = data.sum(axis=0) # Column sums
>>> row_max = data.max(axis=1) # Row maximums
>>> global_min = data.min() # Global minimum
Matrix Splitting and Combining
>>> base = np.mat(np.ones((2, 2)))
>>> extra = np.mat(np.eye(2))
>>> vertical_join = np.vstack((base, extra)) # Vertical concatenation
>>> horizontal_join = np.hstack((base, extra)) # Horizontal concatenation
Converting Between Matrices, Lists, and Arrays
Convert between different data structures:
>>> my_list = [[1, 2], [3, 4]]
>>> my_array = np.array(my_list)
>>> my_matrix = np.mat(my_list)
>>> back_to_list = my_matrix.tolist()
Note: One-dimensional conversions behave different:
>>> simple_list = [5, 6, 7]
>>> mat_version = np.mat(simple_list)
>>> converted_back = mat_version.tolist() # Returns nested list [[5, 6, 7]]
Extract scalar values from 1x1 matrices:
>>> single_val_matrix = np.mat([9])
>>> scalar = single_val_matrix[0, 0] # Extract as integer