show me the golang code for matrix ops
时间: 2024-05-16 10:13:40 浏览: 89
Sure, here's some example Go code for basic matrix operations:
```go
package main
import (
"fmt"
)
type Matrix [][]int
func main() {
// create two matrices
matrix1 := Matrix{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
matrix2 := Matrix{{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}
// print the matrices
fmt.Println("Matrix 1:")
printMatrix(matrix1)
fmt.Println("Matrix 2:")
printMatrix(matrix2)
// perform matrix addition
matrix3 := addMatrices(matrix1, matrix2)
fmt.Println("Matrix 3 (matrix1 + matrix2):")
printMatrix(matrix3)
// perform matrix multiplication
matrix4 := multiplyMatrices(matrix1, matrix2)
fmt.Println("Matrix 4 (matrix1 * matrix2):")
printMatrix(matrix4)
}
func addMatrices(matrix1 Matrix, matrix2 Matrix) Matrix {
rows := len(matrix1)
cols := len(matrix1[0])
result := make(Matrix, rows)
for i := 0; i < rows; i++ {
result[i] = make([]int, cols)
for j := 0; j < cols; j++ {
result[i][j] = matrix1[i][j] + matrix2[i][j]
}
}
return result
}
func multiplyMatrices(matrix1 Matrix, matrix2 Matrix) Matrix {
rows1 := len(matrix1)
cols1 := len(matrix1[0])
rows2 := len(matrix2)
cols2 := len(matrix2[0])
if cols1 != rows2 {
panic("Invalid matrix dimensions for multiplication")
}
result := make(Matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make([]int, cols2)
for j := 0; j < cols2; j++ {
sum := 0
for k := 0; k < cols1; k++ {
sum += matrix1[i][k] * matrix2[k][j]
}
result[i][j] = sum
}
}
return result
}
func printMatrix(matrix Matrix) {
for i := 0; i < len(matrix); i++ {
fmt.Println(matrix[i])
}
fmt.Println()
}
```
This code defines a `Matrix` type as a slice of slices of integers. It then defines functions for adding and multiplying matrices, as well as a function for printing matrices. The `main` function creates two matrices, performs matrix addition and multiplication, and prints the results.
阅读全文