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
Approach
Here's the approach to multiply two matrices in Go, along with the step to check if the multiplication is valid:
Define matrices: Start by defining the two matrices, let's say matrix
and matrix , that you want to multiply. Ensure that the number of columns in matrix matches the number of rows in matrix for valid multiplication. Check validity: Before proceeding, validate if the matrices can be multiplied. Confirm that the number of columns in matrix
is equal to the number of rows in matrix . If this condition is not met, matrix multiplication is not possible. Initialize result matrix: Create an empty result matrix
to store the product. The dimensions of matrix will be the number of rows in matrix and the number of columns in matrix . Perform multiplication: Iterate through the rows of matrix
and the columns of matrix . For each element in matrix (at position ), calculate the sum of the products of corresponding elements from row of matrix and column of matrix .
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 mainimport ("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 multipliedif colsA != rowsB {fmt.Println("Matrix multiplication is not valid.")return nil}// Initialize result matrix CC := make([][]int, rowsA)for i := range C {C[i] = make([]int, colsB)}// Perform multiplicationfor 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 BA := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}B := [][]int{{9, 8}, {6, 5}, {3, 2}}// Perform matrix multiplicationC := multiplyMatrices(A, B)if C != nil {// Display the resultfmt.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
multiplyMatricesfunction takes two matrices,AandB, as input and returns their matrix productC.Lines 8–9: The function determines the dimensions (number of rows and columns) of matrices
AandB.Lines 12–15: It checks if the matrices can be multiplied by comparing the number of columns in matrix
Awith the number of rows in matrixB. If the dimensions are incompatible, the function prints an error message and returnsnil.Lines 18–21: If multiplication is valid, it initializes a new matrix
Cwith the appropriate dimensions to store the result.Lines 25–30: Using nested loops, the function iterates through the rows of matrix
Aand the columns of matrixB. For each elementC[i][j]in the resulting matrix, it computes the sum of the products of corresponding elements from rowiof matrixAand columnjof matrixB.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