We can use NumPy to implement various types of matrices. We mostly use np.array() for every operation in this section.
Import the library:
import numpy as np
A matrix with size m x n (m represents the number of rows, and n represents the number of columns).
# Rectangular Matrices
matrix1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [8, 9, 9, 9]])
print("Matrix 1:\\n", matrix1)
print("Shape:", matrix1.shape)
matrix2 = np.array([[1, 2, 3], [5, 6, 7], [8, 9, 9], [10, 11, 12]])
print("Matrix 2:\\n", matrix2)
print("Shape:", matrix2.shape)
Output:
Matrix 1:
[[1 2 3 4]
[5 6 7 8]
[8 9 9 9]]
Shape: (3, 4)
Matrix 2:
[[ 1 2 3]
[ 5 6 7]
[ 8 9 9]
[10 11 12]]
Shape: (4, 3)
The most common type of matrices. A matrix with size m x n where m = n → Matrix of size n (or Matrix of order n).
A square matrix is also a special type of a rectangular matrix.
# Square Matrices
matrix1 = np.array([[1, 2, 3], [5, 6, 7], [8, 9, 9]])
print("Matrix 1:\\n", matrix1)
print("Shape:", matrix1.shape)
Output:
Matrix 1:
[[1 2 3]
[5 6 7]
[8 9 9]]
Shape: (3, 3)
Optional: Check if the matrix is a square matrix by simply comparing the number of rows and the number of columns.
# Check if the matrix is square
if matrix1.shape[0] == matrix1.shape[1]:
print("The matrix is square.")
else:
print("The matrix is not square.")