Lesson 3
Foundations of Matrix Manipulation
Lesson Overview

Welcome to Foundations of Matrix Manipulation. Here, we’ll dive into two-dimensional data structures, known as matrices. Matrices are essential in various areas of programming, such as machine learning, computer vision, and game development, so it’s important to understand how to effectively traverse and manipulate them.

Example: Accessing Elements in a Matrix

In Ruby, a matrix is simply an array of arrays, with each inner array representing a row. You can access matrix elements by using the row and column indices.

Here’s an example of accessing elements in a Ruby matrix:

Ruby
1matrix = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5] 6 7# Access element in the first row, second column 8element = matrix[0][1] # This will give 2
Efficient Matrix Search

For practice, let’s look at a common task: searching for a target value in a sorted matrix, where each row and column is sorted in ascending order. Given this property, we can perform an efficient search by starting from the top-right corner of the matrix:

  • If the current element equals the target, you’ve found it.
  • If the current element is greater than the target, move left (one column back).
  • If the current element is less than the target, move down (one row forward).

Here’s how this search might be implemented:

Ruby
1def search_matrix(matrix, target) 2 return false if matrix.empty? # Return false if the matrix is empty 3 4 row = 0 5 col = matrix[0].size - 1 # Start from the top-right corner 6 7 while row < matrix.size && col >= 0 8 current = matrix[row][col] 9 10 if current == target 11 return true # Target found 12 elsif current > target 13 col -= 1 # Move left if the current element is larger than the target 14 else 15 row += 1 # Move down if the current element is smaller than the target 16 end 17 end 18 19 false # Target not found after traversing 20end 21 22matrix = [ 23 [1, 4, 7], 24 [2, 5, 8], 25 [3, 6, 9] 26] 27 28target = 5 29puts search_matrix(matrix, target) # Expected output: true

This approach efficiently narrows down the search area at each step, taking advantage of the matrix’s sorted structure.

Ready to Practice?

Once you’re comfortable with these matrix basics, it’s time to dive into practice exercises. Remember, the goal here isn’t just to solve problems but to strengthen your understanding of matrix operations, enhance problem-solving skills, and write efficient, elegant code.

Let’s get started!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.