2

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

mario_nsport
  • 160
  • 8
  • 3
    Lists of lists are really inefficient for storing matrices. You should consider using numpy instead. – wim Nov 11 '20 at 15:54
  • Related/dupe [Most efficient method to find maximum element and list of maximum elements from a 2-d array?](https://stackoverflow.com/q/48195041/674039) – wim Nov 11 '20 at 18:02

3 Answers3

6

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
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

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))
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
1

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
Amit Kumar
  • 613
  • 3
  • 15