How to find consecutive numbers

229 views (last 30 days)
Edward
Edward on 2 Apr 2012
Answered: Adil Sbai on 6 May 2017
So i have an array: a=[16 17 32 33 48 63 79 80 81 97 98 113 114 129 130]
how can i write a program to find where those consecutive numbers are? i've tried using a for loop but haven't really got anywhere.. Please note that at one point there is 3 consecutive numbers.. The idea is each of these numbers is an index of another array: value=[3 0 2 5 3 2 1 0 0 2 7 7 3 7 8]; all equally spaced, which is supposed to mean: realvalue=[30 25 3 2 100 27 73 78]; and im trying to get the array 'realvaue' from arrays 'a' and 'value'

Accepted Answer

Thomas
Thomas on 2 Apr 2012
diff(a)==1
should do the job for you. It will show you where in a you have consecutive values..
a(diff(a)==1)
Gives the first value
or
p=find(diff(a)==1)
q=[p;p+1];
a(q) % this gives all the pairs of consecutive numbers

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 2 Apr 2012
Edited: Andrei Bobrov on 27 Sep 2016
i1 = 1;
C{i1}=a(i1);
for j1 = 2:numel(a)
t = a(j1)-a(j1-1);
if t == 1
C{i1} = [C{i1} a(j1)];
else
i1 = i1 + 1;
C{i1} = a(j1);
end
end
OR
k= find(diff(a)==1);
k1 = [k;k+1];
idx = reshape(k1(k1~=intersect(k,k+1)),2,[]);
C = arrayfun(@(x)a(idx(1,x):idx(2,x)),1:size(idx,2),'un',0)
ADD
i1 = 1;
C(1)=1;
for j1 = 2:numel(a)
t = a(j1)-a(j1-1);
if t == 1
C(i1) = C(i1) + 1;
else
i1 = i1 + 1;
C(i1) = 1;
end
end
v = [3 0 2 5 3 2 1 0 0 2 7 7 3 7 8];
rv = str2double(mat2cell(sprintf('%d',v),1,C))
OR
k= find(diff(a)==1);
k1 = [k;k+1];
idx = reshape(k1(k1~=intersect(k,k+1)),2,[]);
id = sortrows([idx ones(2,1)*setdiff(1:numel(a),k1(:))].',1).';
C = diff(id)+1;
v = [3 0 2 5 3 2 1 0 0 2 7 7 3 7 8];
rv = str2double(mat2cell(sprintf('%d',v),1,C));
Last added
realvalue = accumarray(cumsum([true diff(a) ~= 1])',value',[],@(x)str2double(sprintf('%d',x')))
new add 2016
t = diff(a) == 1;
y = [t,false];
x = xor(y,[false,t]);
ii = cumsum(~(x|y) + y.*x);
out = accumarray(ii(:),value(:),[],@(z)10.^(numel(z)-1:-1:0)*z);
  2 Comments
Arun Badigannavar
Arun Badigannavar on 27 Sep 2016
Does this work on simulink. parameters? what would be the best way to compare consecutive numbers in simulink dd?
yeungor
yeungor on 27 Oct 2016
Andrei definitely seems like a code golfer. Thanks for this, I'm using it to find linear regions in data.

Sign in to comment.


Adil Sbai
Adil Sbai on 6 May 2017
Call this function:
function bool = successive(a)
% Determines if all the numbers in a given input 1D array are successive
% integers.
%
assert((size(a,1)==1 || size(a,2)==1) && isa(a,'double'));
a = sort(a);
bool = (abs(max(a)-min(a))+1)==numel(a);
end
These are examples:
>> successive([-1 4 3 0 2 1])
ans =
1
>> successive([-1 4 3 -3 2 1])
ans =
0

Community Treasure Hunt

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

Start Hunting!