Simple Matrix Practice

Lesson Overview

Welcome to this lesson covering Simple Matrix Operations. This is where we traverse the arena of two-dimensional data structures, commonly known as matrices. Matrices play an instrumental role in many domains of programming, such as machine learning, computer vision, and game development, making it important for you to understand how to effectively manipulate and traverse through them.

Matrix Review

In C++, matrices are often represented using an std::vector of std::vectors. This allows for dynamic resizing and easy manipulation. For example, a 3x3 matrix can be declared and initialized as follows:

C++
std::vector<std::vector<int>> matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

You can access elements of the matrix using indices of the row and column. For example, matrix[1][2] would access the element in the second row and third column, which is 6.

Matrix Traversal Review

We can access the number of rows of a matrix using matrix.size(). The number of columns can be determined by the size of any inner std::vector, such as matrix[0].size(). Traversing a matrix usually involves nested loops. The outer loop normally iterates over the rows, and the inner loop iterates over the columns. Let's take a look at this code that simply prints each element of a matrix.

C++
for (int i = 0; i < matrix.size(); i++) {
    for (int j = 0; j < matrix[i].size(); j++) {
        std::cout << matrix[i][j] << " ";
    }
    std::cout << std::endl;
}

Let's break this code down:

Outer Loop

  • This loop iterates over the rows of the matrix.
  • matrix.size() returns the number of rows in the matrix.
  • The variable i is the row index, starting at 0 and incrementing by 1 until it reaches the total number of rows.
C++
for (int i = 0; i < matrix.size(); i++) {

Inner Loop

  • This loop iterates over the columns of the current row (i).
  • matrix[i].size() returns the number of columns in the i-th row of the matrix.
  • The variable j is the column index, starting at 0 and incrementing by 1 until it reaches the total number of columns in the current row.
C++
for (int j = 0; j < matrix[i].size(); j++) {

Accessing Elements

  • matrix[i][j] accesses the element located at the i-th row and j-th column of the matrix.
  • std::cout << matrix[i][j] << " " prints the accessed element followed by a space " ".
C++
std::cout << matrix[i][j] << " ";

Printing Newline

  • We print a newline character, moving the console cursor to the next line.
C++
std::cout << std::endl;

In summary, the outer loop iterates through each row, while the inner loop iterates through each column of the current row, printing each element followed by a space. After printing all elements in a row, it prints a newline character to start the next row on a new line.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal