Go Tutorials

Go Programs

Go Add Two Matrices


Go Add Two Matrices

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
}


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,

  1. Define a function named addMatrices that takes two parameters a and b, both of type [][]int.
  2. Get the number of rows and columns from the first matrix.
  3. Initialize a result matrix with the same dimensions as the input matrices.
  4. Use nested for loops to iterate through the elements of the matrices.
  5. In each iteration, add the corresponding elements from a and b and store the result in the result matrix.
  6. Return the result matrix.
  7. 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]