Simple Matrix Operations in Go

Lesson Overview

Welcome to this lesson covering Simple Matrix Operations. This is where we explore 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 them.

Matrix Review

In Go, matrices can be represented using slices of slices. This allows us to easily manipulate our data structures while retaining flexibility in specifying the size of the matrix dynamically. Here is an example of how you can declare and initialize a 3x3 matrix in Go:

matrix := [][]int{
    {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 in a matrix using len(matrix). The number of columns can be determined by the length of any inner slice, such as len(matrix[0]). 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.

for i := 0; i < len(matrix); i++ {
    for j := 0; j < len(matrix[i]); j++ {
        fmt.Print(matrix[i][j], " ")
    }
    fmt.Println()
}

Let's break this code down:

Outer Loop

  • This loop iterates over the rows of the matrix.
  • len(matrix) 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.
for i := 0; i < len(matrix); i++ {

Inner Loop

  • This loop iterates over the columns of the current row (i).
  • len(matrix[i]) 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.
for j := 0; j < len(matrix[i]); j++ {

Accessing Elements

  • matrix[i][j] accesses the element located at the i-th row and j-th column of the matrix.
  • fmt.Print(matrix[i][j], " ") prints the accessed element, followed by a space " ".
fmt.Print(matrix[i][j], " ")

Printing Newline

  • We print a newline character, moving the console cursor to the next line.
fmt.Println()

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