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.
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.
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
}
We can create a function to multiply two matrices by taking the dot product of rows and columns.
For example,
multiplyMatrices
that takes two parameters a
and b
, both of type [][]int
.a
, the number of columns from b
, and the number of columns from a
(which must equal the number of rows from b
).a
and the number of columns from b
.for
loops to iterate through the elements of the matrices.a
and column from b
and store the result in the result matrix.multiplyMatrices
function with sample matrices and print the result.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)
}
}
Product of the matrices is: [30 24 18] [84 69 54] [138 114 90]