简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM