Ask Your Question
1

`repr` applied on a matrix

asked 2022-10-22 12:05:00 +0100

po gravatar image

Typically, the repr function returns a string that can be executed and yield the same value as the object. In sageMath, this is not the case for a matrix : repr has the same behaviour as the str function has and str applied to a matrix returns a "nice" representation of it:

M=matrix([[1, 1],[1, 1]])

print(repr(M)==str(M)) 
print(M)

printing

True
[1 1]
[1 1]

This is not the behaviour I was expecting. To compare with Numpy:

from numpy import array

M = array([[1, 1], [1, 1]])

print(repr(M))
print()
print(M)

outpouting

array([[1, 1],
       [1, 1]])

[[1 1]
 [1 1]]

Do I need to write my own repr function when applied to a matrix?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-10-22 12:21:11 +0100

slelievre gravatar image

Both repr and str aim to provide human-readable string representations.

They coincide for small Sage matrices, but differ for matrix size above 20.

Indeed, try the following:

sage: a = zero_matrix(ZZ, 20)
sage: a
20 x 20 dense matrix over Integer Ring (use the '.str()' method to see the entries)
sage: repr(a)
'20 x 20 dense matrix over Integer Ring'
sage: str(a)
'[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]'

Some Sage objects have a sage_input method giving code to recreate them.

It is the case for integer matrices:

sage: M = matrix([[1, 1], [1, 1]])
sage: sage_input(M)
matrix(ZZ, [[1, 1], [1, 1]])
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-10-22 12:05:00 +0100

Seen: 167 times

Last updated: Oct 22 '22