RE: sort and find in MATHEMATI
- To: mathgroup@smc.vnet.net
- Subject: [mg11081] RE: [mg11021] sort and find in MATHEMATI
- From: Ersek_Ted%PAX1A@mr.nawcad.navy.mil
- Date: Wed, 18 Feb 1998 20:32:32 -0500
A. Jerschow wrote: ---------- |in MATLAB I would write: | |[dummy,index]=sort(a(:,i)); |sorta=a(index,:); | |to sort the matrix a by it's i-th column. | |What's the easiest way to do the same in MATHEMATICA ? | First we make a matrix of random integers called (data). In[1]:= data=Table[{Random[Integer,{0,10}], Random[Integer,{0,2}], Random[Integer,{50,60}]},{i,8}] Out[1]= {{7,1,58},{4,1,60},{3,0,50},{1,0,58},{9,2,53},{1,1,51},{3,0,54},{8,2,53}} Note: If you use TableForm[data] or MatrixForm[data] the data are displayed as a Table or a Matrix. The two forms are very similar. In the line below we sort the data on the second column. In general we use OrderedQ[{#1[[n]], #2[[n]]}]& to Sort on column (n). In[2]:= Sort[data,OrderedQ[{#1[[2]],#2[[2]]}]&] Out[2]= {{3,0,50},{1,0,58},{3,0,54},{7,1,58},{4,1,60},{1,1,51},{9,2,53},{8,2,53}} The Mathematica syntax for this is a bit cryptic. Let me know if you want me to explain more about this (#1[[2]], #2[[2]]) business. Excuse me for my lack of modesty , but I think I have a better explanation than anything else I have found. A novice might be tempted to do this using a Do loop or For loop, etc. But that is much less efficient using Mathematica. | |Another thing, again MATLAB: | |index=find(a(:,i) == 0); |sorta=a(index,:); | |to remove lines, which have zeros in the i-th column. | The following removes all data that have zero for the second element. In[3]:= Select[data,(#[[2]]!=0)& ] Out[3]= {{7,1,58},{4,1,60},{9,2,53},{1,1,51},{8,2,53}} In the following lines I show you how to do some other things that are very useful. We can perform an operation f[] on the third column of data. In[4]:= data/.{x_,y_,z_}->{x,y,f[z]} Out[4]= {{7,1,f[58]},{4,1,f[60]},{3,0,f[50]},{1,0,f[58]},{9,2,f[53]},{1,1,f[51]},{3, 0, f[54]},{8,2,f[53]}} We can swap the second and third columns. In[5]:= data/.{x_,y_,z_}->{x,z,y} Out[5]= {{7,58,1},{4,60,1},{3,50,0},{1,58,0},{9,53,2},{1,51,1},{3,54,0},{8,53,2}} That's all for now. Ted Ersek