Multiply Two Matrices in Go



In this tutorial, we will learn how to multiply two matrices in Go. We will cover the basic concept of matrix multiplication and implement a function to perform the operation.


What is Matrix Multiplication

Matrix multiplication is the process of multiplying two matrices by taking the dot product of rows and columns. The number of columns in the first matrix must be equal to the number of rows in the second matrix.


Syntax

The syntax to multiply two matrices in Go is:

func multiplyMatrices(a, b [][]int) [][]int {
    rowsA := len(a)
    colsA := len(a[0])
    colsB := len(b[0])
    result := make([][]int, rowsA)
    for i := range result {
        result[i] = make([]int, colsB)
    }
    for i := 0; i < rowsA; i++ {
        for j := 0; j < colsB; j++ {
            for k := 0; k < colsA; k++ {
                result[i][j] += a[i][k] * b[k][j]
            }
        }
    }
    return result
}


Example 1: Multiplying two matrices

We can create a function to multiply two matrices by taking the dot product of rows and columns.

For example,

  1. Define a function named multiplyMatrices that takes two parameters a and b, both of type [][]int.
  2. Get the number of rows from a, the number of columns from b, and the number of columns from a (which must equal the number of rows from b).
  3. Initialize a result matrix with dimensions equal to the number of rows from a and the number of columns from b.
  4. Use nested for loops to iterate through the elements of the matrices.
  5. In each iteration, calculate the dot product of the corresponding row from a and column from b and store the result in the result matrix.
  6. Return the result matrix.
  7. In the main function, call the multiplyMatrices function with sample matrices and print the result.

Go Program

package main

import (
    "fmt"
)

func multiplyMatrices(a, b [][]int) [][]int {
    rowsA := len(a)
    colsA := len(a[0])
    colsB := len(b[0])
    result := make([][]int, rowsA)
    for i := range result {
        result[i] = make([]int, colsB)
    }
    for i := 0; i < rowsA; i++ {
        for j := 0; j < colsB; j++ {
            for k := 0; k < colsA; k++ {
                result[i][j] += a[i][k] * b[k][j]
            }
        }
    }
    return result
}

func main() {
    // Sample matrices
    a := [][]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }
    b := [][]int{
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1},
    }

    // Multiply the matrices
    result := multiplyMatrices(a, b)

    // Print the result
    fmt.Println("Product of the matrices is:")
    for _, row := range result {
        fmt.Println(row)
    }
}

Output

Product of the matrices is:
[30 24 18]
[84 69 54]
[138 114 90]