sam
sam

Reputation: 19164

Creating norm of an numpy array

I have this numpy array

X = [[ -9.03525007   7.45325017  33.34074879][ -6.63700008   5.13299996  31.66075039][ -5.12724996   8.25149989  30.92599964][ -5.12724996   8.25149989  30.92599964]]

I want to get the norm of this array using numpy. How can I do that?

for every array inside, I need sqrt(x2+y2+z2), so my output wull be array of 4 values (since there are 4 inside arrays)

Upvotes: 4

Views: 876

Answers (4)

ssm
ssm

Reputation: 5373

Other people have already given you the norm() function. You are probably looking to map() the norm() function within the array.

Just do:

from numpy.linalg import norm
norms = map(norm, x)

Upvotes: 0

chthonicdaemon
chthonicdaemon

Reputation: 19760

To get what you ask for (the 2-norm of each row in your array), you can use the axis argument to numpy.linalg.norm:

import numpy
x = numpy.array([[ -9.03525007,   7.45325017,  33.34074879],
                 [ -6.63700008,   5.13299996,  31.66075039],
                 [ -5.12724996,   8.25149989,  30.92599964],
                 [ -5.12724996,   8.25149989,  30.92599964]])
print numpy.linalg.norm(x, axis=1)

=> 

array([ 35.33825423,  32.75363451,  32.41594355,  32.41594355])

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34146

Why don't use numpy.linalg.norm

import numpy

x = [[ -9.03525007, 7.45325017 , 33.34074879], [ -6.63700008  , 5.13299996  , 31.66075039], [ -5.12724996 , 8.25149989 , 30.92599964], [ -5.12724996   , 8.25149989  , 30.92599964]]

print numpy.linalg.norm(x)

Output:

66.5069889437

Upvotes: 2

James Mills
James Mills

Reputation: 19030

Did you mean matrix norm(s)? If so:

import numpy as np
>>> xs = [[ -9.03525007, 7.45325017, 33.34074879], [-6.63700008, 5.13299996, 31.66075039], [-5.12724996, 8.25149989, 30.92599964], [-5.12724996, 8.25149989, 30.92599964]]
>>> np.linalg.norm(xs)
66.506988943656381

See: http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html

Upvotes: 1

Related Questions