YohanRoth
YohanRoth

Reputation: 3263

Computing matrix norms without loop in numpy

How do I compute matrix norms within (100, 8, 8) matrix such that I have 100 norm-list vector at the end? E.g I want the norm of every 8x8 matrix.

Right now I do, but it is probably too inefficient and ugly

norms = []
for m in mats:
    norms.append(np.linalg.norm(m, ord='fro'))

Upvotes: 1

Views: 947

Answers (4)

Simon Crane
Simon Crane

Reputation: 2182

You can do this with a list comprehension:

norms = [np.linalg.norm(m, ord='fro') for m in mats]

Or with numpy.vectorize:

@np.vectorize
def my_fun(m):
    return np.linalg.norm(m, ord='fro')

norms = my_fun(mats)

Upvotes: 0

Igor Rivin
Igor Rivin

Reputation: 4864

foo = mats.reshape(100, -1)
np.sqrt(np.diagonal(foo @ foo.T))

(this is specifically for the Frobenius norm).

Upvotes: 0

Warren Weckesser
Warren Weckesser

Reputation: 114956

numpy.linalg.norm accepts an axis argument that can be a tuple holding the two axes that hold the matrices. So your calculation is simply

norms = np.linalg.norm(m, ord='fro', axis=(1, 2))

For example,

In [43]: import numpy as np

In [44]: rng = np.random.default_rng()

In [45]: m = rng.uniform(0, 3, size=(10, 8, 8))

In [46]: norms = np.linalg.norm(m, ord='fro', axis=(1, 2))

In [47]: norms
Out[47]: 
array([15.43326187, 12.18174753, 12.72366662, 14.20558871, 14.08558457,
       13.51040102, 13.38476228, 14.3334069 , 15.19745515, 14.46134742])

Upvotes: 5

Marco Cerliani
Marco Cerliani

Reputation: 22031

list(map(lambda x: np.linalg.norm(x, ord='fro'), mats))

Upvotes: 1

Related Questions