douchao9899 2019-02-21 08:34
浏览 362
已采纳

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

Here is the piece of code:

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 :
%v

", mat.Formatted(A, mat.Prefix(""), mat.Excerpt(0)))

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

", 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

When I use size to determine the dimensions of the matrix A. Then it gives me an error undefined: size.

How can I get dimensions of the matrix A?

  • 写回答

3条回答 默认 最新

  • dongyan2469 2019-02-21 13:26
    关注

    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.


    For example,

    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:
    %v
    
    ", 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)
    }
    

    Output:

    A matrix:
    ⎡ 1   2   3⎤
    ⎢ 4   5   6⎥
    ⎢ 7   8   9⎥
    ⎣10  11  12⎦
    
    A: rows:  4
    A: cols:  3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案