Transpose a Matrix in Go



In this tutorial, we will learn how to transpose a matrix in Go. We will cover the basic concept of matrix transposition and implement a function to perform the operation.


What is Matrix Transposition

Matrix transposition is the process of swapping the rows and columns of a matrix. The element at row i and column j of the original matrix becomes the element at row j and column i in the transposed matrix.


Syntax

The syntax to transpose a matrix in Go is:

func transposeMatrix(a [][]int) [][]int {
    rows := len(a)
    cols := len(a[0])
    result := make([][]int, cols)
    for i := range result {
        result[i] = make([]int, rows)
    }
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            result[j][i] = a[i][j]
        }
    }
    return result
}


Example 1: Transposing a matrix

We can create a function to transpose a matrix by swapping its rows and columns.

For example,

  1. Define a function named transposeMatrix that takes one parameter a of type [][]int.
  2. Get the number of rows and columns from the input matrix.
  3. Initialize a result matrix with the dimensions swapped.
  4. Use nested for loops to iterate through the elements of the matrix.
  5. In each iteration, assign the element at row i and column j of the input matrix to row j and column i of the result matrix.
  6. Return the result matrix.
  7. In the main function, call the transposeMatrix function with a sample matrix and print the result.

Go Program

package main

import (
    "fmt"
)

func transposeMatrix(a [][]int) [][]int {
    rows := len(a)
    cols := len(a[0])
    result := make([][]int, cols)
    for i := range result {
        result[i] = make([]int, rows)
    }
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            result[j][i] = a[i][j]
        }
    }
    return result
}

func main() {
    // Sample matrix
    a := [][]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    // Transpose the matrix
    result := transposeMatrix(a)

    // Print the result
    fmt.Println("Transposed matrix is:")
    for _, row := range result {
        fmt.Println(row)
    }
}

Output

Transposed matrix is:
[1 4 7]
[2 5 8]
[3 6 9]