# How to Create Square and Rectangle Matrices in Python

A matrix is a collection of numbers arranged in a fixed number of rows and columns.

The size or shape of a matrix is defined by its number of rows and columns and is often denoted as m x n, where m is the number of rows and n is the number of columns.

A square matrix is a matrix where the number of rows (m) equals the number of columns (n). Here’s how you can create a square matrix in Python:

import numpy as np

# Create a 3x3 square matrix
square_matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

print("Square Matrix:\n", square_matrix)
print("The shape of this Square Matrix is", square_matrix.shape)


Output:

Square Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]

The shape of this Square Matrix is (3, 3)


The .shape attribute of a NumPy array is a property that returns a tuple representing the dimensions of the array. For matrices, this attribute provides the number of rows (m) and columns(n), which is helpful to verify that your matrix is indeed a square with 3 rows and 3 columns.

A rectangular matrix, in contrast, has a differing number of rows and columns. Below is how to create a 2×3 matrix (two rows, three columns) using NumPy:

import numpy as np

# Create a 2x3 rectangular matrix
rectangular_matrix = np.array([[1, 2, 3],
[4, 5, 6]])

print("Rectangular Matrix:\n", rectangular_matrix)
print("The shape of this Rectangular Matrix is", rectangular_matrix.shape)


Output:

Rectangular Matrix:
[[1 2 3]
[4 5 6]]

The shape of this Rectangular Matrix is (2, 3)


The .shape attribute confirms that the matrix is indeed rectangular with 2 rows and 3 columns. This ensures that the data structure matches the intended design.

To further illustrate the flexibility in creating matrices of different shapes, let’s construct a 4×2 rectangular matrix (four rows and two columns):

import numpy as np

# Create a 4x2 rectangular matrix
rectangular_matrix_4x2 = np.array([[10, 20],
[30, 40],
[50, 60],
[70, 80]])

print("Rectangular Matrix:\n", rectangular_matrix_4x2)
print("The shape of this Rectangular Matrix is", rectangular_matrix_4x2.shape)


Output:

Rectangular Matrix:
[[10 20]
[30 40]
[50 60]
[70 80]]

The shape of this Rectangular Matrix is (4, 2)


Once again, the .shape attribute confirms that the matrix is indeed rectangular with 4 rows and 2 columns.

Familiarity with the shape and structure of matrices is a valuable first step as you encounter many different types of matrices. Knowing how to check the dimensions of your matrices helps ensure that basic operations such as matrix addition, multiplication, and transformation are performed correctly. Mastering these foundational aspects sets a strong basis for tackling more advanced topics and applications in the future.