CatarinaCM
CatarinaCM

Reputation: 1245

Adding numpy matrices together

I've several matrices, each one stored in a NumPy array and I would like to add them all.

a1=np.load("20130101T054446")
a2=np.load("20130102T205729")
a3=np.load("20130104T153006")
a4=np.load("20130113T130758")
a5=np.load("20130113T212154")

I know its possible to add them in this away:

z=a1+a2+a3+a4+a5

But, since I have hundreds of matrices I would like to do it in a easy away.

Is there any way to import all at the same time and ascribe it to different variables?

Upvotes: 1

Views: 357

Answers (2)

Alex Riley
Alex Riley

Reputation: 176770

To avoid creating a lot of matrices in memory, it might be best to read them in one at a time and add them in place.

Start by loading your first matrix:

z = np.load("20130101T054446")

Then read the remaining matrices in one at a time adding each one to z as you go:

matrices = ["20130102T205729", "20130104T153006", "20130113T130758",  "20130113T212154"]

for m in matrices:
    z += np.load(m)

Upvotes: 2

Carsten
Carsten

Reputation: 18446

Instead of loading each dataset into a different variable, you could create a list of all datasets you want to load, load them into a list, and then sum them up.

import numpy as np

datasets = ["20130101T054446",
    "20130102T205729",
    "20130104T153006",
    "20130113T130758",
    "20130113T212154"] # easy to extend if you have more of them

a = [np.load(d) for d in datasets]

z = np.sum(a, axis=0)

Upvotes: 0

Related Questions