MATLAB Answers

0

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

Asked by Skylar Kim on 5 Mar 2019
Latest activity Commented on by Skylar Kim on 6 Mar 2019
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...
Could you please help me?
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

  0 Comments

Sign in to comment.

Tags

3 Answers

Answer by Andrei Bobrov
on 5 Mar 2019
Edited by Andrei Bobrov
on 5 Mar 2019
 Accepted Answer

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

Answer by Jos (10584)
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]) ].'

Answer by Walter Roberson
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 .

  1 Comment

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]

Sign in to comment.