[Numpy-discussion] Vector magnitude?
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
> 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 : numpy.linalg.norm?
Base Class: <type 'function'>
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.
"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