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,
- Define a function named
transposeMatrix
that takes one parametera
of type[][]int
. - Get the number of rows and columns from the input matrix.
- Initialize a result matrix with the dimensions swapped.
- Use nested
for
loops to iterate through the elements of the matrix. - In each iteration, assign the element at row
i
and columnj
of the input matrix to rowj
and columni
of the result matrix. - Return the result matrix.
- 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]