如何在 go-lang 中获取矩阵的维数?

How can get the dimension of a matrix in go-lang?

这是一段代码:

package main
import (
 "fmt"
 "gonum.org/v1/gonum/mat"
)
func main() {
  // Matrix and Vector

  // Initialize a Matrix A
  row1 := []float64{1,2,3}
  row2 := []float64{4,5,6}
  row3 := []float64{7,8,9}
  row4 := []float64{10,11,12}

  A := mat.NewDense(4,3,nil)
  A.SetRow(0, row1)
  A.SetRow(1, row2)
  A.SetRow(2, row3)
  A.SetRow(3, row4)

  fmt.Printf("A :\n%v\n\n", mat.Formatted(A, mat.Prefix(""), mat.Excerpt(0)))

  // Initialize a Vector v
  v := mat.NewDense(3,1, []float64{1,2,3})
  fmt.Printf("v :\n%v\n\n", mat.Formatted(v, mat.Prefix(""), mat.Excerpt(0)))

  //Get the dimension of the matrix A where m = rows and n = cols
  row, col := len(A)
  // row, col := size(A)
  fmt.Println("row: ", row)
  fmt.Println("col: ", col)

}

Error: invalid argument A (type *mat.Dense) for len

当我使用size来确定矩阵A的维度时。然后它给我一个错误undefined: size

如何获得矩阵的维度 A

len 用于数组、切片等内置类型

从包的文档中,您应该使用Dims()来访问行大小和列大小

尝试 godoc gonum.org/v1/gonum/mat 并找到以下部分:

func (m *Dense) Dims() (r, c int)
Dims returns the number of rows and columns in the matrix.

您可以使用 Dims() 方法获取矩阵中的行数和列数。

参见:https://godoc.org/gonum.org/v1/gonum/mat#Dense.Dims

package mat

import "gonum.org/v1/gonum/mat" 

func (*Dense) Dims

func (m *Dense) Dims() (r, c int)

Dims returns the number of rows and columns in the matrix.


例如,

package main

import (
    "fmt"

    "gonum.org/v1/gonum/mat"
)

func main() {
    row1 := []float64{1, 2, 3}
    row2 := []float64{4, 5, 6}
    row3 := []float64{7, 8, 9}
    row4 := []float64{10, 11, 12}

    A := mat.NewDense(4, 3, nil)
    A.SetRow(0, row1)
    A.SetRow(1, row2)
    A.SetRow(2, row3)
    A.SetRow(3, row4)

    fmt.Printf("A matrix:\n%v\n\n", mat.Formatted(A, mat.Prefix(""), mat.Excerpt(0)))

    //Get the dimensions of the matrix A
    rows, cols := A.Dims()
    fmt.Println("A: rows: ", rows)
    fmt.Println("A: cols: ", cols)
}

输出:

A matrix:
⎡ 1   2   3⎤
⎢ 4   5   6⎥
⎢ 7   8   9⎥
⎣10  11  12⎦

A: rows:  4
A: cols:  3