## Finding the first and the last elements of consecutive numbers and combining them with a semi colon.

### Skylar Kim (view profile)

on 5 Mar 2019
Latest activity Commented on by Skylar Kim

on 6 Mar 2019

### Andrei Bobrov (view profile)

Hello,
I need to make an array of the first and the last number of a consecutive numbers and combine them with a delimator(;).
I need this format of an array ;
answer = [1 5; 10; 20 23]
When given this kind of input;
outliers = [1 2 3 4 5 10 20 21 22 23];
This is my code so far, but I have no idea how to combine the result into one array...
Thank you.
outliers = [1 2 3 4 5 10 20 21 22 23];
grouped = mat2cell( outliers, 1, diff( [0, find(diff(outliers) ~= 1), length(outliers)] )) ;
for group_idx = 1:length(grouped)
first = [cellfun(@(x)x(1),grouped)];
last = [cellfun(@(x)x(end),grouped)];
format = sprintf(['%.0f ' '%.0f;'], [first(group_idx) last(group_idx)])
end

### Andrei Bobrov (view profile)

on 5 Mar 2019
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 5 Mar 2019

ii = cumsum([true,diff(outliers)~=1]);
A = accumarray(ii(:),outliers(:),[],@(x){[min(x),max(x)]});
out = reshape([A{:}],2,[])';

Skylar Kim

### Skylar Kim (view profile)

on 6 Mar 2019
Thank you so much!!

### Jos (10584) (view profile)

on 5 Mar 2019

Using diff and logical indexing, this turns out to be quite simple:
outliers = [1 2 3 4 5 10 20 21 22 23];
TF = diff(outliers) ~= 1 ;
out = [outliers([true TF]) ; outliers([TF true]) ].'

Skylar Kim

### Skylar Kim (view profile)

on 6 Mar 2019
Beautiful code! Thank you!

### Walter Roberson (view profile)

on 5 Mar 2019

That is not possible in matlab . In matlab all rows of a numeric array must be the same length .
You can create a character vector . Or you can create a cell array .

Skylar Kim

### Skylar Kim (view profile)

on 5 Mar 2019
Thank you so much for your time. If it is impossible, then is it possible to make it as below?
answer = [1 5; 10 10; 20 23]