Matrix Transpose With Slices

Rebuild a matrix with rows and columns exchanged through nested loops over a fresh [][]int, keeping the source untouched for shape-aware transformations.

GoData Integrity

Code

gosnippet
24 lines
package main

import "fmt"

// transpose swaps rows and columns into a fresh slice of slices
func transpose(matrix [][]int) [][]int {
	rows, cols := len(matrix), len(matrix[0])
	out := make([][]int, cols)
	for c := 0; c < cols; c++ {
		out[c] = make([]int, rows)
		for r := 0; r < rows; r++ {
			out[c][r] = matrix[r][c]
		}
	}
	return out
}

func main() {
	grid := [][]int{{1, 2, 3}, {4, 5, 6}}
	for _, row := range transpose(grid) {
		fmt.Println(row)
	}
	fmt.Println(transpose([][]int{{7}}))
}

Matrix Transpose With Slices: what runs and why

Matrix Transpose With Slices is built around the functions transpose and main.

for c := 0; c < cols; c++ is the per-item workhorse.

Points of care

  • No package manager enters the picture — each call lands on a built-in.

Putting it to use

Signature: func transpose(matrix [][]int) [][]int

main calls 1 helper in sequence: transpose.

Core lines

func transpose(matrix [][]int) [][]int {
	rows, cols := len(matrix), len(matrix[0])
	out := make([][]int, cols)
	for c := 0; c < cols; c++ {
		out[c] = make([]int, rows)
		for r := 0; r < rows; r++ {
			out[c][r] = matrix[r][c]
		}
	}
	return out
}
for _, row := range transpose(grid) {
	fmt.Println(row)
}

Interactive Tools for This Topic

FAQ

How do you run Matrix Transpose With Slices?
Nothing to install first — run the file and the program does the rest.