我正在Go中实现矩阵 - 矩阵乘法算法,我无法推理如何就地更改输出矩阵。我已尝试将输入更改为指针,但 2D 切片不能是指针?
package main
import (
"fmt"
"strconv"
"math/rand"
"os"
"time"
)
func main() {
L := len(os.Args)
m, n, p, q, err := mapVars(L, os.Args)
if err != 0 {
fmt.Fprintf(os.Stderr, "error: Incorrect command line arguments.\n")
os.Exit(1)
}
fmt.Println("The product array has dimensions.")
fmt.Printf("\tC is %dx%d\n", m, q)
fmt.Println("\nPopulating matrix A.")
A, _ := createMat(m, n)
fmt.Println("Matrix A.")
printMat(m, A)
fmt.Println("\nPopulating matrix B.")
B, _ := createMat(p, q)
fmt.Println("Matrix B.")
printMat(p, B)
fmt.Println("\nPerforming row-wise matrix-matrix multiplication AB.")
startRow := time.Now()
C := rowMultMat(m, n, q, A, B)
dtRow := time.Since(startRow)
fmt.Printf("Time elapsed: %v\n", dtRow)
fmt.Println("Matrix C.")
printMat(q, C)
}
func mapVars(l int, args []string) (m int, n int, p int, q int, err int) {
if l == 2 {
m, _ := strconv.Atoi(args[1])
n, _ := strconv.Atoi(args[1])
p, _ := strconv.Atoi(args[1])
q, _ := strconv.Atoi(args[1])
fmt.Printf("Creating two arrays, A, B, with square dimensions.\n")
fmt.Printf("\tA is %dx%d\n\tB is %dx%d\n", m, n, p, q)
return m, n, p, q, 0
} else if (l == 5 || n != p) {
m, _ := strconv.Atoi(args[1])
n, _ := strconv.Atoi(args[2])
p, _ := strconv.Atoi(args[3])
q, _ := strconv.Atoi(args[4])
fmt.Println("Creating two arrays, A, B, with dimensions.")
fmt.Printf("\tA is %dx%d\n\tB is %dx%d\n", m, n, p, q)
return m, n, p, q, 0
} else {
fmt.Println("Incorrect command line arguments.\n")
return 0, 0, 0, 0, 1
}
}
目前,我正在初始化内部的矩阵,因为我无法作为指针传递到2D切片。例如,将 2x3 乘以 3x2,得到 2x2。rowMultMatCrun main.go 2 3 3 2
沧海一幻觉
相关分类