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

7 次查看(过去 30 天)
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

采纳的回答

Andrei Bobrov
Andrei Bobrov 2019-3-5
编辑:Andrei Bobrov 2019-3-5
ii = cumsum([true,diff(outliers)~=1]);
A = accumarray(ii(:),outliers(:),[],@(x){[min(x),max(x)]});
out = reshape([A{:}],2,[])';

更多回答(2 个)

Jos (10584)
Jos (10584) 2019-3-5
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]) ].'

Walter Roberson
Walter Roberson 2019-3-5
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 .

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by