Ask Your Question

# maximum element of a matrix  How to determine the maximum element of a matrix? For "matrix_integer_dense" there is height() . For numpy matrix there is max function. How to do it in Sage matrices with one single "max" like instruction ?

 Alternetive: m.numpy().max()

edit retag close merge delete

## Comments

I do not think there is any... an other alternative would be max(m.list()) which I do not like because it explicitely build the list of the entries of m.

## 2 Answers

Sort by » oldest newest most voted I tried to do this a while ago but couldn't do it in one step. I just went through all the columns and got their maximum. I also needed to find the location of the maximum.

Example for a matrix M with type 'sage.matrix.matrix_real_double_dense.Matrix_real_double_dense'

MAX_val=0
for i in range(len(M.columns())):
if (MAX_val< max(M.column(i))):
MAX_val=max(M.column(i))


MAX_val is then the maximum value in the matrix. I hope it was helpful. I ll follow to see if there is a better way.

more

Not a single command, but you can try the following one-line possibilities:

sage: size = 1000
sage: m = random_matrix(RDF, size)

sage: max(max(i for i in rows) for rows in m)
sage: max(m[i,j] for i in range(size) for j in range(size))
sage: max(m.list())
sage: max(m._list())


From the slowest to the fastest (5.19 s, 3.1 s, 2.12 s, 2.08 s).

more

## Comments

You forget "m.numpy().max()" which is around 2ms and is definitely the best solution in that case. The reason is that a matrix over RDF is a wrapper to a numpy matrix.

You are right, and the bad timings of the privious methods could come from there too, here are the timings for a matrix over RR: sage: size = 1000 sage: m = random_matrix(RR, size) m.numpy().max() # 2.14 s max(max(i for i in rows) for rows in m) # 862 ms max(m[i,j] for i in range(size) for j in range(size)) # 414 ms max(m.list()) # 232 ms max(m._list()) # 137 ms

And over ZZ, from the slowest to the fastest: sage: m = random_matrix(ZZ, size) m.numpy().max() # 2.53 s max(max(i for i in rows) for rows in m) # 1.03 s max(m.list()) # 430 ms max(m[i,j] for i in range(size) for j in range(size)) # 365 ms max(m._list()) # 359 ms

## Your Answer

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

Add Answer

## Stats

Asked: 2013-07-11 05:44:26 +0200

Seen: 3,258 times

Last updated: Jul 11 '13