Skip to content
Advertisement

is there any way to calculate L2 norm of multiple 2d matrices at once, in python?

for example, I have a matrix of dimensions (a,b,c,d). I want to calculate L2 norm of all d matrices of dimensions (a,b,c). Is there any way to use numpy.linalg.norm with out any looping structure? I mean, the resultant array should be 1 x d

Advertisement

Answer

How about this?

import numpy as np
mat      = np.arange(2*3*4*5).reshape(2,3,4,5)  # create 4d array
mat2     = np.moveaxis(mat,-1,0)     # bring last axis to the front
*outarr, = map(np.linalg.norm,mat2)  # use map

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement