tags:

views:

42

answers:

2
+3  Q: 

Tidying up a list

I'm fairly sure there should be an elegant solution to this (in MATLAB), but I just can't think of it right now.

I have a list with [classIndex, start, end], and I want to collapse consecutive class indices into one group like so:

This

 1     1    40
 2    46    53
 2    55    55
 2    57    64
 2    67    67
 3    68    91
 1    94   107

Should turn into this

 1     1    40
 2    46    67
 3    68    91
 1    94   107

How do I do that?

EDIT

Never mind, I think I got it - it's almost like fmarc's solution, but gets the indices right

a=[  1     1    40
     2    46    53
     2    55    55
     2    57    64
     2    67    67
     3    68    91
     1    94   107];

d = diff(a(:,1));
startIdx = logical([1;d]);
endIdx   = logical([d;1]);
b = [a(startIdx,1),a(startIdx,2),a(endIdx,3)];
+1  A: 

One way to do it if the column in question is numeric: Build the differences along the id-column. Consecutive identical items will have zero here:

diffind = diff(a(:,1)');

Use that to index your array, using logical indexing.

b = a([true [diffind~=0]],:);

Since the first item is always included and the difference vector starts with the difference from first to second element, we need to prepend one true value to the list.

fmarc
Thanks! Your solution doesn't get the 'ends' right, but it put me on the right track. +1
Jonas
+2  A: 

Here is one solution:

Ad = find([1; diff(A(:,1))]~=0);
output = A(Ad,:);
output(:,3) = A([Ad(2:end)-1; Ad(end)],3);
clear Ad
yuk
Yes, this is what I was looking for.
Jonas

related questions