Python matrix add diagonal elements

advertisements

I need to make a small program that will take a 4x4 matrix and add the diagonal of the of the columns and rows.

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

Like this would add 1+2+3+4.

Sorry for being vague, this is what I came up with for adding a matrix by each column straight down. I also have not been using numpy yet.

matrix = [1,2,3,4],[5,6,7,8],[9,10,11,12] #Assume a list is given
total = 0
    for column in range(0, len(matrix[0])):
        for row in range(0, len(matrix)):
            total += matrix[row][column]
        print("Sum for column " + str(column) + " is " + str(total))
        total = 0   #Reset total to zero before restarting count

I'm not 100% where to start with this so any ideas would be great. My teacher told us offset as a hint.


The diagonal elements are at the same row-column coordinates:

matrix = [[1,2,3,4],
          [1,2,3,4],
          [1,2,3,4],
          [1,2,3,4]]
answer = sum(matrix[i][i] for i in range(len(matrix)))