Calculate the average of a matrix

Asked

Viewed 347 times

2

I was trying to calculate the average of a matrix without using numpy, but n managed to get to the desired algorithm

def mediah(matriz:List):
    soma = 0
    for linha in matriz:
        for aij in linha:
                soma += aij
    return soma/len(matriz)

This was the code I was able to get to, but the type of operation on line 5 is not supported.

1 answer

3


The problem is that len(matriz) returns the number of rows in the matrix, not the number of elements. Since you are going through the matrix, you can add in a variable the size of each row to get the total amount of values.

def media(matriz):
  soma = 0
  tamanho = 0

  for linha in matriz:
    soma += sum(linha)
    tamanho += len(linha)

  return soma / tamanho

Browser other questions tagged

You are not signed in. Login or sign up in order to post.