How to multiply matrices in Go

Matrix multiplication is a fundamental operation in linear algebra and numerical computing. We will explore the concept of matrix multiplication and delve into how to implement it using the Go programming language. Matrix multiplication is crucial in various scientific and engineering applications, including machine learning, computer graphics, and simulations.

Matrix multiplication

Here's the mathematical procedure for multiplying two matrices. Before performing the multiplication, it's essential to ensure that the number of columns in the first matrix corresponds to the number of rows in the second matrix. Let's illustrate this with the following instance:

We can see that AA is 3×3 3 \times 3 and B is 3×2 3 \times 2. We can see that multiplication AB AB is possible because the first matrix AA has 33 columns, and the matrix BB has 33 rows, which means the column of matrix A equals the rows of matrix B.

Approach

Here's the approach to multiply two matrices in Go, along with the step to check if the multiplication is valid:

  1. Define matrices: Start by defining the two matrices, let's say matrix AA and matrix BB, that you want to multiply. Ensure that the number of columns in matrix AA matches the number of rows in matrix BB for valid multiplication.

  2. Check validity: Before proceeding, validate if the matrices can be multiplied. Confirm that the number of columns in matrix AA is equal to the number of rows in matrix BB. If this condition is not met, matrix multiplication is not possible.

  3. Initialize result matrix: Create an empty result matrix CC to store the product. The dimensions of matrix CC will be the number of rows in matrix AA and the number of columns in matrix BB.

  4. Perform multiplication: Iterate through the rows of matrix AA and the columns of matrix BB. For each element in matrix CC (at position [i][j][i][j]), calculate the sum of the products of corresponding elements from row ii of matrix AA and column jj of matrix BB.

Code

In this code, the multiplyMatrices function performs matrix multiplication following the outlined approach. It includes a validity check and displays whether the multiplication is valid. Make sure to adjust the matrix dimensions and values according to your needs.

Here's the Go code snippet that implements this approach:

package main
import (
"fmt"
)
func multiplyMatrices(A, B [][]int) [][]int {
rowsA, colsA := len(A), len(A[0])
rowsB, colsB := len(B), len(B[0])
// Check if matrices can be multiplied
if colsA != rowsB {
fmt.Println("Matrix multiplication is not valid.")
return nil
}
// Initialize result matrix C
C := make([][]int, rowsA)
for i := range C {
C[i] = make([]int, colsB)
}
// Perform multiplication
for i := 0; i < rowsA; i++ {
for j := 0; j < colsB; j++ {
for k := 0; k < colsA; k++ {
C[i][j] += A[i][k] * B[k][j]
}
}
}
return C
}
func printMatrix(matrix [][]int) {
for _, row := range matrix {
fmt.Println(row)
}
}
func main() {
// Define matrices A and B
A := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
B := [][]int{{9, 8}, {6, 5}, {3, 2}}
// Perform matrix multiplication
C := multiplyMatrices(A, B)
if C != nil {
// Display the result
fmt.Println("Matrix A:")
printMatrix(A)
fmt.Println("Matrix B:")
printMatrix(B)
fmt.Println("Product of Matrices A and B:")
printMatrix(C)
}
}
  • Lines 7–33: The multiplyMatrices function takes two matrices, A and B, as input and returns their matrix product C.

    • Lines 89: The function determines the dimensions (number of rows and columns) of matrices A and B.

    • Lines 12–15: It checks if the matrices can be multiplied by comparing the number of columns in matrix A with the number of rows in matrix B. If the dimensions are incompatible, the function prints an error message and returns nil.

    • Lines 18–21: If multiplication is valid, it initializes a new matrix C with the appropriate dimensions to store the result.

    • Lines 25–30: Using nested loops, the function iterates through the rows of matrix A and the columns of matrix B. For each element C[i][j] in the resulting matrix, it computes the sum of the products of corresponding elements from row i of matrix A and column j of matrix B.

    • Line 32: After calculating the matrix product, the function returns the resulting matrix C.

The multiplyMatrices function encapsulates the process of matrix multiplication, including dimension checks and element calculations, providing a convenient way to compute the product of two matrices in Go.

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved