Element432
Element432

Reputation: 71

Python matrix add diagonal elements

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.

Upvotes: 3

Views: 2995

Answers (2)

dabhand
dabhand

Reputation: 517

Simple using numpy

>>> import numpy as np
>>> matrix = [[1,2,3,4],
              [1,2,3,4],
              [1,2,3,4],
              [1,2,3,4]]
>>> sum(np.diag(matrix))
10

Upvotes: 3

inspectorG4dget
inspectorG4dget

Reputation: 113915

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)))

Upvotes: 3

Related Questions