[Numpy-discussion] Vector magnitude?

Robert Kern robert.kern@gmail....
Wed Sep 5 13:57:17 CDT 2007

Robert Dailey wrote:
> Thanks for your response.
> I was not able to find len() in the numpy documentation at the following
> link:
> http://www.scipy.org/doc/numpy_api_docs/namespace_index.html
> <http://www.scipy.org/doc/numpy_api_docs/namespace_index.html>
> Perhaps I'm looking in the wrong location?

It's a Python builtin function, but it doesn't do what you want. It returns the
number of elements in a sequence (any sequence, not just arrays) not the
magnitude of the vector.

Besides constructing the Euclidean norm itself (as shown by others here), you
can also use numpy.linalg.norm() to calculate any of several different norms of
a vector or a matrix:

In [7]: numpy.linalg.norm?
Type:             function
Base Class:       <type 'function'>
Namespace:        Interactive
Definition:       numpy.linalg.norm(x, ord=None)
    norm(x, ord=None) -> n

    Matrix or vector norm.


      x -- a rank-1 (vector) or rank-2 (matrix) array
      ord -- the order of the norm.

       For arrays of any rank, if ord is None:
         calculate the square norm (Euclidean norm for vectors,
         Frobenius norm for matrices)

       For vectors ord can be any real number including Inf or -Inf.
         ord = Inf, computes the maximum of the magnitudes
         ord = -Inf, computes minimum of the magnitudes
         ord is finite, computes sum(abs(x)**ord,axis=0)**(1.0/ord)

       For matrices ord can only be one of the following values:
         ord = 2 computes the largest singular value
         ord = -2 computes the smallest singular value
         ord = 1 computes the largest column sum of absolute values
         ord = -1 computes the smallest column sum of absolute values
         ord = Inf computes the largest row sum of absolute values
         ord = -Inf computes the smallest row sum of absolute values
         ord = 'fro' computes the frobenius norm sqrt(sum(diag(X.H * X),axis=0))

       For values ord < 0, the result is, strictly speaking, not a
       mathematical 'norm', but it may still be useful for numerical purposes.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the Numpy-discussion mailing list