BigTim
BigTim

Reputation: 27

How do I get the sum of a matrix efficiently?

I have a problem in Python, I have a matrix that looks something like this: [[2, 3, 5, 1], [5, 1, 6, 3]] and I tried using a for statement but that was too slow for my problem, what is an efficient way of doing this?

Upvotes: 2

Views: 34

Answers (1)

Glatinis
Glatinis

Reputation: 347

You can use the numpy library to do this, a bonus is that numpy is extra fast than native Python, let me give you an example.

import numpy as np

matrix = [[2, 3, 5, 1], [5, 1, 6, 3]]
summedMatrix = np.matrix(matrix).sum()

print(summedMatrix)

Upvotes: 1

Related Questions