On Thursday 20 November 2008 11:11:14 Hans Meine wrote:
> I have a 2D matrix comprising a sequence of vectors, and I want to compute
> the norm of each vector. np.linalg.norm seems to be the best bet, but it
> does not support axis. Wouldn't this be a nice feature?
Here's a basic implementation. docstring + tests not updated yet, also I
wonder whether axis should be the first argument, but that could create
compatibility problems.
Ciao,
Hans
Index: numpy/linalg/linalg.py
===================================================================
--- numpy/linalg/linalg.py (revision 6085)
+++ numpy/linalg/linalg.py (working copy)
@@ -1324,7 +1324,7 @@
st = s[:min(n, m)].copy().astype(_realType(result_t))
return wrap(x), wrap(resids), results['rank'], st
-def norm(x, ord=None):
+def norm(x, ord=None, axis=None):
"""
Matrix or vector norm.
@@ -1365,20 +1365,24 @@
"""
x = asarray(x)
nd = len(x.shape)
- if ord is None: # check the default case first and handle it immediately
+ if axis is not None:
+ nd = 1
+ if ord is None:
+ ord = 2
+ elif ord is None: # check the default case first and handle it immediately
return sqrt(add.reduce((x.conj() * x).ravel().real))
- if nd == 1:
+ if nd == 1 or axis is not None:
if ord == Inf:
- return abs(x).max()
+ return abs(x).max(axis)
elif ord == -Inf:
- return abs(x).min()
+ return abs(x).min(axis)
elif ord == 1:
- return abs(x).sum() # special case for speedup
+ return abs(x).sum(axis) # special case for speedup
elif ord == 2:
- return sqrt(((x.conj()*x).real).sum()) # special case for speedup
+ return sqrt(((x.conj()*x).real).sum(axis)) # special case for speedup
else:
- return ((abs(x)**ord).sum())**(1.0/ord)
+ return ((abs(x)**ord).sum(axis))**(1.0/ord)
elif nd == 2:
if ord == 2:
return svd(x, compute_uv=0).max()
_______________________________________________
Numpy-discussion mailing list
[email protected]
http://projects.scipy.org/mailman/listinfo/numpy-discussion