First time here? Check out the FAQ!

Ask Your Question
1

maximum element of a matrix

asked 11 years ago

Pedro gravatar image

updated 10 years ago

FrédéricC gravatar image

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

[1] http://www.sagemath.org/doc/reference...

[2] Alternetive: m.numpy().max()

Preview: (hide)

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.

vdelecroix gravatar imagevdelecroix ( 11 years ago )

2 Answers

Sort by » oldest newest most voted
1

answered 11 years ago

tmonteil gravatar image

updated 11 years ago

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

Preview: (hide)
link

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.

vdelecroix gravatar imagevdelecroix ( 11 years ago )

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

tmonteil gravatar imagetmonteil ( 11 years ago )

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

tmonteil gravatar imagetmonteil ( 11 years ago )
0

answered 11 years ago

M. H. M. gravatar image

updated 11 years ago

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.

Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 11 years ago

Seen: 5,157 times

Last updated: Jul 11 '13