[SciPy-user] unique, sort, sortrows

David M. Kaplan David.Kaplan@ird...
Sat Jul 26 13:06:51 CDT 2008


I am fairly new to numpy/scipy (switching from matlab).  I have noticed
a few things that left me confused.  I am wondering if I could get some
input from others.

1) On the webpage: http://www.scipy.org/NumPy_for_Matlab_Users , where
it says matlab sortrows(a,i) is equivalent to a[argsort(a[:,0],i)], I
believe this should be a[argsort(a[:,i]),:].  Or better yet:

matlab: [b,I] = sortrows(a,i)
numpy: I = argsort(a[:,i]), b = a[I,:]

I have already changed this on the webpage, but I want to make sure I am
not missing something.

2) Is there a simple equivalent of sortrows(a) (i.e., sorting by entire
rows)?  Similarly, is there a simple equivalent of the matlab Y =
unique(X,'rows')?  I looked online and there appears to have been
previous discussion of these, but nothing simple and general seemed to
come out.

3) Is there an equivalent of [Y,I,J] = unique(X)?  In this case, I is
the indices of the unique elements and J is an index from Y to X (i.e.,
where the unique elements appear in X.  I can get I with:

I,Y = unique1d( X, return_index=True )

but J, which is very useful, is not available.  I suppose I could do:

J = array([])
for i,y in enumerate(Y):
	J[ nonzero( y == X ) ] = i

But it seems like J is useful enough that there should be an easier way
(or perhaps it should be integrated into unique1d, at the risk of adding
more keyword arguments).

4) What is the best equivalent of meshgrid(x,y,z,...) or
ndgrid(x,y,z...)?  I defined my own function, but is there a built in

def ndgrid( *args ):
	s = []
	for a in args:
	I = indices(s)
	res = []
	for a,i in zip(args,I):
	return res

This method will also be painful for large matrices as one has to create
twice as much data (the index matrix and the resulting matrices).

5) I was trying to do matrix multiplication of matrices with more than 2
axes.  Normally matrix multiplication of an [M,N,P] matrix with a
[P,Q,R] matrix should produce something with dimensions [M,N,Q,R], but
this produces an error.  What is the appropriate idiom for this?

Thanks for the help.


David M. Kaplan
Charge de Recherche 1
Institut de Recherche pour le Developpement
Centre de Recherche Halieutique Mediterraneenne et Tropicale
av. Jean Monnet
B.P. 171
34203 Sete cedex

Phone: +33 (0)4 99 57 32 27
Fax: +33 (0)4 99 57 32 95

More information about the SciPy-user mailing list