Two-Dimensional Arrays (Matrices)

beginner
15 min

Two-Dimensional Arrays (Matrices)

Welcome to our guide on Two-Dimensional Arrays (also known as Matrices)! Today, we'll explore this powerful data structure, understand its real-world applications, and learn how to work with it in code. Let's dive in!

šŸŽÆ Understanding Two-Dimensional Arrays

A Two-Dimensional Array (Matrix) is an array that consists of rows and columns. Each element can be accessed using two indices, just like coordinates on a map.

šŸ“ Note: A Two-Dimensional Array is similar to a list of lists, where each list represents a row.

šŸ’” Creating a Two-Dimensional Array

In most programming languages, you can create a Two-Dimensional Array using the following syntax:

python
matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

Here, matrix is our Two-Dimensional Array, and each inner list represents a row.

šŸ“ Accessing and Modifying Matrix Elements

To access an element in a Matrix, you use two indices separated by a comma:

python
print(matrix[1][1]) # Output: 4

To modify an element, simply assign a new value:

python
matrix[1][1] = 99 print(matrix) # Output: [[0, 1, 2], [3, 99, 5], [6, 7, 8]]

šŸŽÆ Common Matrix Operations

  1. Transpose: Swapping rows and columns.
python
def transpose(matrix): transposed = [] for i in range(len(matrix[0])): transposed_row = [] for j in range(len(matrix)): transposed_row.append(matrix[j][i]) transposed.append(transposed_row) return transposed matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(transpose(matrix)) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  1. Determinant: A value that can be computed for square matrices (matrices with the same number of rows and columns).
python
def determinant(matrix): if len(matrix) == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] determinant_value = 0 for c in range(len(matrix)): submatrix = [] for r in range(1, len(matrix)): submatrix_row = [] for s in range(len(matrix[0])): if s != c: submatrix_row.append(matrix[r][s]) submatrix.append(submatrix_row) determinant_value += ((-1) ** c) * matrix[0][c] * determinant(submatrix) return determinant_value matrix = [[1, 2], [3, 4]] print(determinant(matrix)) # Output: 5

šŸ’” Pro Tip:

Matrix operations can be used in various real-world applications, such as solving systems of linear equations, image processing, and game development.

Quiz

Quick Quiz
Question 1 of 1

What is a Two-Dimensional Array (Matrix) in simple terms?

Happy coding! Let's master Two-Dimensional Arrays together! šŸ¤