Python Program to Print an Identity Matrix

1. Introduction

An identity matrix is a square matrix with ones on the diagonal and zeros elsewhere. It is a key concept in linear algebra and has the property that any matrix multiplied by the identity matrix is unchanged. This post presents a Python program to print an identity matrix of a given size.

An identity matrix is defined as a square matrix with ones on the main diagonal and zeros in all other positions. The main diagonal is the diagonal that runs from the top left corner to the bottom right corner.

2. Program Steps

1. Define the size of the matrix.

2. Iterate over rows and columns to print the appropriate values.

3. Use nested loops: the outer loop for rows and the inner loop for columns.

4. Print '1' when the row and column indices are equal, and '0' otherwise.

3. Code Program

# Function to print an identity matrix of size n
def print_identity_matrix(n):
    # Iterate over each row
    for i in range(n):
        # Iterate over each column
        for j in range(n):
            # Print 1 if the current row and column are the same (diagonal), else 0
            print(1 if i == j else 0, end=" ")
        # Move to the next line after each row
        print()

# Size of the identity matrix
matrix_size = 4
# Print the identity matrix
print_identity_matrix(matrix_size)

Output:

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Explanation:

1. print_identity_matrix is a function that prints an identity matrix of size n.

2. The function uses two nested for loops, where i represents each row and j represents each column.

3. In the inner loop, print(1 if i == j else 0, end=" ") is used to print 1 if the row index i is equal to the column index j (indicating a diagonal element), otherwise 0.

4. end=" " specifies that each print statement ends with a space instead of a newline character, allowing the elements of a row to be printed on the same line.

5. After the inner loop finishes printing a row, print() is called to move to the next line before printing the next row.

6. Calling print_identity_matrix(matrix_size) with matrix_size set to 4 prints a 4x4 identity matrix.

7. The output is a 4x4 identity matrix with 1s on the diagonal and 0s elsewhere, formatted with spaces between elements and newlines after each row.

Comments