Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: anouncing STRSORT.M
Replies: 0

 Pope P. Britt Posts: 134 Registered: 12/7/04
anouncing STRSORT.M
Posted: Aug 19, 1996 2:05 PM

After many false starts, I think I've got a routine that will
sort a matrix consisting of rows of text or or numbers.

Example 1:

X=str2mat('catnip','cat','dog','apple','cantelope','dingo')

X =
catnip
cat
dog
apple
cantelope
dingo

[y,i]=strsort(X)

y =
apple
cantelope
cat
catnip
dingo
dog

i =
4
5
2
1
6
3

example 2:

X=rand(4)+j*rand(4)

X =
0.6295 + 0.4679i 0.8886 + 0.5717i 0.5133 + 0.4985i 0.8415 +
0.8907i
0.7362 + 0.2872i 0.2332 + 0.8024i 0.5911 + 0.9554i 0.2693 +
0.6248i
0.7254 + 0.1783i 0.3063 + 0.0331i 0.8460 + 0.7483i 0.4154 +
0.8420i
0.9995 + 0.1537i 0.3510 + 0.5344i 0.4121 + 0.5546i 0.5373 +
0.1598i

[x,i]=strsort(X)

x =
0.7254 + 0.1783i 0.3063 + 0.0331i 0.8460 + 0.7483i 0.4154 +
0.8420i
0.6295 + 0.4679i 0.8886 + 0.5717i 0.5133 + 0.4985i 0.8415 +
0.8907i
0.7362 + 0.2872i 0.2332 + 0.8024i 0.5911 + 0.9554i 0.2693 +
0.6248i
0.9995 + 0.1537i 0.3510 + 0.5344i 0.4121 + 0.5546i 0.5373 +
0.1598i

i =
3
1
2
4

example 3: (from Mark Smart 8/13/96)

A=[0 1 1;1 0 1;1 1 0;2 1 0;1 3 1];
X=A(randperm(size(A,1)),:)

X1=[sum((X.*X)')',X];
Y=strsort(X1);
Y(:,1)=[]

X =
2 1 0
1 3 1
1 0 1
0 1 1
1 1 0

Y =
0 1 1
1 0 1
1 1 0
2 1 0
1 3 1

Has any one got a better way to do it?

Pete Britt
pete@electrosystems.com

________________________________________

function [Y,I]=strsort(X);
%STRSORT Sort by row in ascending order.
% STRSORT(X) considers each row of X as a word
% and sorts in ascending order of words.
% When X is complex, the elements are sorted by ABS(X).
% [Y,I] = STRSORT(X) also returns an index vector I.
%
% Pope P. Britt, August 1996
% pete@electrosystems.com

[m,n]=size(X);
Y=[X,(1:m)'];
[a,I]=sort(Y(:,1));
Y=Y(I,:);
if all(diff(abs(Y(:,1)))~=0);
Y(:,n+1)=[];return;
end;
for i=n:-1:1;
[a,I]=sort(Y(:,i));
Y=Y(I,:);
end;
I=abs(Y(:,n+1));
Y=X(I,:);
Y(:,n+1)=[];