-1

I have a matrix (in Sage) in a notebook - through Jupyter.

How do I find the size of this matrix in Sage? I know in Python I can find the length of a list with

len(list)

Is there, in Sage, a function that does this, but with a matrix? Kinda like

len(matrix)

Example when I try it:

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()

Same with:

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

Thanks! Appreciate any help.

Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27
William Martens
  • 753
  • 1
  • 8
  • 27

1 Answers1

1

Use the methods

  • nrows for the number of rows
  • ncols for the number of columns
  • dimensions for both at once

Example:

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)

To get the number of elements:

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

Other variations:

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

Explanation:

  • list(a) gives the list of rows (as vectors)
  • a.T is the transpose matrix
  • a.list() gives the list of entries
  • a.dense_coefficient_list() also gives that
  • a.coefficients() gives a list of nonzero entries

Details:

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]

More possibilities:

sage: sum(1 for row in a for entry in row)
6
sage: sum(1 for _ in a.list())
6
Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27