Add Two Matrices in Go
In this tutorial, we will learn how to add two matrices in Go. We will cover the basic concept of matrix addition and implement a function to perform the operation.
What is Matrix Addition
Matrix addition is the process of adding two matrices by adding the corresponding entries together. The two matrices must have the same dimensions for the addition to be possible.
Syntax
The syntax to add two matrices in Go is:
func addMatrices(a, b [][]int) [][]int {
rows := len(a)
cols := len(a[0])
result := make([][]int, rows)
for i := range result {
result[i] = make([]int, cols)
}
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
result[i][j] = a[i][j] + b[i][j]
}
}
return result
}
Example 1: Adding two matrices
We can create a function to add two matrices element-wise by iterating through their elements and adding the corresponding entries.
For example,
- Define a function named
addMatrices
that takes two parametersa
andb
, both of type[][]int
. - Get the number of rows and columns from the first matrix.
- Initialize a result matrix with the same dimensions as the input matrices.
- Use nested
for
loops to iterate through the elements of the matrices. - In each iteration, add the corresponding elements from
a
andb
and store the result in the result matrix. - Return the result matrix.
- In the main function, call the
addMatrices
function with sample matrices and print the result.
Go Program
package main
import (
"fmt"
)
func addMatrices(a, b [][]int) [][]int {
rows := len(a)
cols := len(a[0])
result := make([][]int, rows)
for i := range result {
result[i] = make([]int, cols)
}
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
result[i][j] = a[i][j] + b[i][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},
}
// Add the matrices
result := addMatrices(a, b)
// Print the result
fmt.Println("Sum of the matrices is:")
for _, row := range result {
fmt.Println(row)
}
}
Output
Sum of the matrices is: [10 10 10] [10 10 10] [10 10 10]