Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number of column of the maximum element of a row in a matrix

I want to see the position of the maximum element in each row.

Input:
arr = [[3, 4, 1, 8],
       [1, 4, 9, 11],
       [76, 34, 21, 1],
       [2, 1, 4, 5]]

Output:
[3, 3, 0, 3]

I have already implemented this function, but I don’t know why it’s not working. Please help me.

# Python program to find maximum
# element of each row in a matrix
 
# importing numpy
import numpy
 
# Function to get max element
def maxelement(arr):
    listmax = []
     
    # get number of rows and columns
    no_of_rows = len(arr)
    no_of_column = len(arr[0])
     
    for i in range(no_of_rows):
         
        # Initialize max1 to 0 at beginning
        # of finding max element of each row
        max1 = 0
        for j in range(no_of_column):
            if arr[i][j] > max1 :
                max1 = arr[i][j]
                
        # print maximum element of each row
        listmax.append(max1)
        
    return(listmax)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of appending the maximum value (max1) you want to append the index of the maximum:

# Python program to find maximum
# element of each row in a matrix
 
# importing numpy
import numpy
 
# Function to get max element
def maxelement(arr):
    listmax = []
     
    # get number of rows and columns
    no_of_rows = len(arr)
    no_of_column = len(arr[0])
     
    for i in range(no_of_rows):
         
        # Initialize max1 to 0 at beginning
        # of finding max element of each row
        max1 = 0
        max_index = 0
        for j in range(no_of_column):
            if arr[i][j] > max1 :
                max1 = arr[i][j]
                max_index = j
                
        # print maximum index of each row
        listmax.append(max_index)
        
    return(listmax)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading