mario_nsport
mario_nsport

Reputation: 160

Return the maximun of a matrix

I want to return the max value of a matrix. For example this is my matrix:

matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]

I want to return the max so here '10'

This is my code but I have an error:

max = 0
for i in range(len(matrix)+1):
   for j in range(len(matrix[0])+1):
      if matrix[i][j] > matrix[i+1][j+1]:
         max =  matrix[i][j]
print(max)

Thanks in advance

Upvotes: 2

Views: 240

Answers (3)

pho
pho

Reputation: 25489

Multiple ways to do it:

  1. Fix your method. In Python, lists are zero-based so you need to only iterate from i = 0 to len(matrix) - 1. Doing for i in range(len(matrix)): does this for you. You don't need to do range(len(matrix) + 1)). Also, you should only replace the current maxval if the element you're looking at is greater than maxval.

So,

maxval = -9999999
for i in range(len(matrix)):
   for j in range(len(matrix[i])):
      if matrix[i][j] > maxval: 
         maxval =  matrix[i][j]
print(maxval)
# Out: 10

Or, a more pythonic way is to iterate over the elements instead of accessing them through their indices

maxval = -9999999
for row in matrix:
    for element in row:
        if element > maxval:
            maxval = element

# maxval: 10

Notice I use maxval instead of max so as not to shadow python's inbuilt max() function.

  1. Use numpy (if you're already using it for other things). Like wim mentioned in their comment, a numpy array is a much better way to store matrices instead of lists of lists. Why? See this question
import numpy as np

matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]

maxval = np.max(matrix)
# maxval: 10
  1. Iterate over rows, create a list of max values in each row. Then find the max of this list
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]

rowmax = [max(row) for row in matrix]
maxval = max(rowmax)

# or in one line:
maxval = max(max(row) for row in matrix)
  1. Use map. This is essentially the same as the previous method.
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]

maxval = max(map(max, matrix))

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 633

you can try this.

matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
max1 = 0
for sub_list in  matrix:
    for item in sub_list:
        if item>max1:
            max1=item

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61910

There are several issues with your code, I suggest you use the max function:

matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]

result = max(max(row) for row in matrix)
print(result)

Output

10

Upvotes: 6

Related Questions