Permutations: {0-7, 8-15, 16-23, 24-31}, neater code?

6 views (last 30 days)
I have a set of data (note that the second column is dependent on the first column, and I only care about sorting the first column). Each set is 4 rows:
0 234.23
3 23.423
19 235.32
20 23.43
%line
0 23.54
8 234.43
16 23.42
24 353.43
etc.
Right now I have something that resembles the following:
i=1; j=1;
data=trigsort2(dat);
DCB=zeros((10),(2));
ACB=zeros((10),(2));
DCA=zeros((10),(2));
ACA=zeros((10),(2));
for i = 1:1:length(data)-4;
% Case 4.0:
if data(i,1) >= 0 && data(i,1) <= 7
% Case 4.0.16:
if data(i+1,1) >= 16 && data(i+1,1) <= 23
% Case 4.0.16.8:
if data(i+2,1) >= 8 && data(i+2,1) <= 15
if data(i+3,1) >= 24 && data(i+3,1) <= 31
DCB(j,:) = [data(i,1), data(i,2)];
ACB(j,:) = [data(i+1,1), data(i+1,2)];
DCA(j,:) = [data(i+2,1), data(i+2,2)];
ACA(j,:) = [data(i+3,1), data(i+3,2)];
i = i+4;
j = j+1;
else
i = i+4;
end
% Case 4.0.16.24:
The code repeats for all possible permutations of {0-7, 8-15, 16-23, 24-31}. I'm wondering if there's a more compact way of writing this out, rather than sorting through all of the cases. And yes, they have to be in sequence. And yes, the above sample data would be sorted out of the final data set because its a {0-7, 0-7, 16-23, 16-23}. I basically want my program to cut and sort, I'm hoping I can do this a bit neater.

Accepted Answer

Sean de Wolski
Sean de Wolski on 18 Jul 2011
perhaps
doc sortrows
?
  1 Comment
Lena Heffern
Lena Heffern on 20 Jul 2011
Wow. DUH. Of course!
function [DCB, ACB, DCA, ACA] = eventsorter(dat)
i=1; j=1;
data=trigsort2(dat);
DCB=zeros((10),(2));
ACB=zeros((10),(2));
DCA=zeros((10),(2));
ACA=zeros((10),(2));
while i < length(data)-4;
dat=data(i:i+3,1:2);
dat=sortrows(dat);
if dat(1,1) > 7
i=i+4;
elseif dat(2,1) > 15 | dat(2,1) < 8
i=i+4;
elseif dat(3,1) > 24 | dat(3,1) < 16
i=i+4;
elseif dat (4,1) < 25
i=i+4;
else
DCB(j,:) = [dat(1,1), dat(1,2)];
DCA(j,:) = [dat(2,1), dat(2,2)];
ACB(j,:) = [dat(3,1), dat(3,2)];
ACA(j,:) = [dat(4,1), dat(4,2)];
i = i+4;
j = j+1;
end
end
end

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 18 Jul 2011
% Reshape the array so that first plane is the sortable numbers
rd = reshape(data,4,[],2)
% Identify the groupings (e.g. {0,7}-->1, {8-15}-->2)
bin = floor(rd(:,:,1)/8)+1
% Identify the unique bin permutations.
% The third output gives an index to each unique permutation
[uniqueBin,indexToUniqueBin,indexFromUniqueBinBackToAll] = unique(bin','rows')
The variable "indexFromUniqueBinBackToAll" is an index to each possible permutation of your first-column variable. You should be able to use that index to fill your output variables. It was not perfectly clear to me how you wanted to sort them in the end, so I left it here.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!