5

I can sum the items in column zero fine. But where do I change the code to sum column 2, or 3, or 4 in the matrix? I'm easily stumped.

def main():
    matrix = []

    for i in range(2):
        s = input("Enter a 4-by-4 matrix row " + str(i) + ": ") 
        items = s.split() # Extracts items from the string
        list = [ eval(x) for x in items ] # Convert items to numbers   
        matrix.append(list)

    print("Sum of the elements in column 0 is", sumColumn(matrix))

def sumColumn(m):
    for column in range(len(m[0])):
        total = 0
        for row in range(len(m)):
            total += m[row][column]
        return total

main()

6 Answers 6

13

numpy could do this for you quite easily:

def sumColumn(matrix):
    return numpy.sum(matrix, axis=1)  # axis=1 says "get the sum along the columns"

Of course, if you wanted do it by hand, here's how I would fix your code:

def sumColumn(m):
    answer = []
    for column in range(len(m[0])):
        t = 0
        for row in m:
            t += row[column]
        answer.append(t)
    return answer

Still, there is a simpler way, using zip:

def sumColumn(m):
    return [sum(col) for col in zip(*m)]
Sign up to request clarification or add additional context in comments.

3 Comments

I guess axis = 0 gets the sum along the columns
Oh no, he is right. If you specify ´axis = 1´, for every row in the matrix, the columns values will be added up and then stored. The result will be a 1D array containing all the sums.
Based on the documentation, for columns we use axis = 0 and for row axis = 1.
8

One-liner:

column_sums = [sum([row[i] for row in M]) for i in range(0,len(M[0]))]

also

row_sums = [sum(row) for row in M]

for any rectangular, non-empty matrix (list of lists) M. e.g.

>>> M = [[1,2,3],\
>>>     [4,5,6],\
>>>     [7,8,9]]
>>>
>>> [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
[12, 15, 18] 
>>> [sum(row) for row in M]
[6, 15, 24]

1 Comment

As much as I like list comprehension magic, @inspectorG4dget's zip based version is ~2X faster for a small (3x3) matrix. zip is 1.86usec vs 3.7usec per loop for nested list comprehension. Old school list(map(sum,zip(*M))) is just as fast (1.87usec).
2

Here is your code changed to return the sum of whatever column you specify:

def sumColumn(m, column):
    total = 0
    for row in range(len(m)):
        total += m[row][column]
    return total

column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))

Comments

2

To get the sum of all columns in the matrix you can use the below python numpy code:

matrixname.sum(axis=0)

1 Comment

Mmm i think it is matrixname.sum(axis=1) instead ... >>> b array([[1, 2], [3, 4]]) >>> b.sum(axis=1) array([3, 7]) >>> b.sum(axis=0) array([4, 6])
2
import numpy as np
np.sum(M,axis=1)

where M is the matrix

Comments

0

This can be made easier if you represent the matrix as a flat array:

m = [
    1,2,3,4,
    10,11,12,13,
    100,101,102,103,
    1001,1002,1003,1004
]

def sum_column(m, n):
    return sum(m[i] for i in range(n, 4 * 4, 4))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.