Matrix Multiplication in Go
This document provides a Go program to multiply two matrices along with a detailed explanation of the program structure and documentation.
Program Structure
The Go program is structured as follows:
- Define the main package and import necessary packages.
- Define a function to multiply two matrices.
- In the main function, initialize two matrices and call the multiplication function.
- Print the result.
Go Program
package main
import (
"fmt"
)
// multiplyMatrices multiplies two matrices A and B and returns the result matrix.
func multiplyMatrices(A, B [][]int) ([][]int, error) {
rowsA, colsA := len(A), len(A[0])
rowsB, colsB := len(B), len(B[0])
if colsA != rowsB {
return nil, fmt.Errorf("number of columns in A must be equal to number of rows in B")
}
// Initialize the result matrix with zero values
C := make([][]int, rowsA)
for i := range C {
C[i] = make([]int, colsB)
}
// Perform matrix 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, nil
}
func main() {
// Initialize two matrices
A := [][]int{
{1, 2, 3},
{4, 5, 6},
}
B := [][]int{
{7, 8},
{9, 10},
{11, 12},
}
// Multiply the matrices
C, err := multiplyMatrices(A, B)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print the result matrix
fmt.Println("Result of matrix multiplication:")
for _, row := range C {
fmt.Println(row)
}
}
Explanation
The program starts by defining the main package and importing the fmt
package for formatting and printing.
The multiplyMatrices
function takes two 2D slices (matrices) as input and returns the product matrix. It first checks if the number of columns in the first matrix is equal to the number of rows in the second matrix, which is a prerequisite for matrix multiplication. If this condition is not met, an error is returned.
The function then initializes the result matrix with dimensions equal to the number of rows of the first matrix and the number of columns of the second matrix, filling it initially with zeros. It performs the matrix multiplication using three nested loops:
- The outer loop iterates over the rows of the first matrix.
- The middle loop iterates over the columns of the second matrix.
- The inner loop performs the dot product of the row of the first matrix and the column of the second matrix.
Finally, the result matrix is returned. In the main
function, two matrices are initialized, and the multiplyMatrices
function is called to multiply them. If an error occurs, it is printed; otherwise, the result matrix is printed.