【问题标题】:Is there a Sage function for finding the length of a matrix?是否有用于查找矩阵长度的 Sage 函数?
【发布时间】:2021-03-12 09:15:01
【问题描述】:

我在笔记本中有一个矩阵(在 Sage 中) - 通过 Jupyter。

如何在 Sage 中找到这个矩阵的大小? 我知道在 Python 中我可以找到列表的长度

len(list)

在 Sage 中是否有一个函数可以做到这一点,但使用矩阵? 有点像

len(matrix)

我尝试的例子:

len([1, 2, 3])
3

len(matrix([[1, 2, 3], [4, 5, 6]]))
TypeError: object of type sage.matrix.matrix_integer_dense.Matrix_integer_dense' has no len()

同理:

aMatrix = matrix([[1, 2, 3], [4, 5, 6]])
aMatrix
len(aMatrix)

谢谢!感谢任何帮助。

【问题讨论】:

  • 感谢您的帮助;再次 - 真的很欣赏它。 //祝您和未来的读者周末愉快!

标签: arrays python-3.x matrix jupyter-notebook sage


【解决方案1】:

使用方法

  • nrows 表示行数
  • ncols 列数
  • dimensions 两者同时使用

例子:

sage: a = matrix([[1, 2, 3], [4, 5, 6]])
sage: a
[1 2 3]
[4 5 6]

sage: a.nrows()
2
sage: a.ncols()
3
sage: a.dimensions()
(2, 3)

获取元素个数:

sage: a.nrows() * a.ncols()
6
sage: prod(a.dimensions())
6

其他变体:

sage: len(list(a))
2
sage: len(list(a.T))
3
sage: len(a.list())
6

解释:

  • list(a) 给出行列表(作为向量)
  • a.T是转置矩阵
  • a.list() 给出条目列表
  • a.dense_coefficient_list() 也给出了这一点
  • a.coefficients() 给出了一个非零条目列表

详情:

sage: list(a)
[(1, 2, 3), (4, 5, 6)]
sage: a.T
[1 4]
[2 5]
[3 6]
sage: a.list()
[1, 2, 3, 4, 5, 6]

更多可能性:

sage: sum(1 for row in a for entry in row)
6
sage: sum(1 for _ in a.list())
6

【讨论】:

  • 这是一个绝妙的答案!非常感谢!也非常Pythonic! :)
猜你喜欢
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 2015-11-17
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多