elnino
elnino

Reputation: 173

Sum of matrices using np.add()

I have a list of n matrices where n = 5:

[matrix([[3.62425112, 0.00953506],
        [0.00953506, 1.05054417]]), matrix([[4.15808905e+00, 9.27845937e-04],
        [9.27845937e-04, 9.88509628e-01]]), matrix([[3.90560856, 0.0504297 ],
        [0.0504297 , 0.92587046]]), matrix([[ 3.87347073, -0.12430547],
        [-0.12430547,  1.09071475]]), matrix([[ 3.87697392, -0.00475038],
        [-0.00475038,  1.01439917]])]

I want to do element-wise addition of these matrices:

I am trying this:

np.add(S_list[0], S_list[1], S_list[2], S_list[3], S_list[4])

It works but I don't want to fix n = 5

Can anyone please help? Thank you.

Upvotes: 0

Views: 43

Answers (3)

George
George

Reputation: 338

Are you sure that np.add(S_list[0], S_list[1], S_list[2], S_list[3], S_list[4]) works ? Because np.add() takes as input arguments two arrays . Anyway , the following code does the work if you want to use np.add():

sum = np.add(S_list[0],S_list[1])

for i in range(len(S_list) - 2):
    sum = np.add(sum,S_list[i+2])

print(sum)

Upvotes: 0

Lior Cohen
Lior Cohen

Reputation: 5735

by the documentation, np.add should add only two matrices.

However np.add.reduce(S_list) or just sum(S_list) will give you what you want.

Upvotes: 1

Mitchell Olislagers
Mitchell Olislagers

Reputation: 1817

You could just use Python's built-in function sum

sum(S_list)

Output:

[[19.43839338 -0.06816324]
 [-0.06816324  5.07003818]]

Upvotes: 0

Related Questions