How to find consecutive numbers

조회 수: 307 (최근 30일)
Edward
Edward 2012년 4월 2일
답변: Adil Sbai 2017년 5월 6일
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'

채택된 답변

Thomas
Thomas 2012년 4월 2일
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
  댓글 수: 1
ping pong
ping pong 2014년 2월 13일
편집: ping pong 2014년 2월 13일
working,its good

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2012년 4월 2일
편집: Andrei Bobrov 2016년 9월 27일
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
Arun Badigannavar
Arun Badigannavar 2016년 9월 27일
Does this work on simulink. parameters? what would be the best way to compare consecutive numbers in simulink dd?
yeungor
yeungor 2016년 10월 27일
Andrei definitely seems like a code golfer. Thanks for this, I'm using it to find linear regions in data.

댓글을 달려면 로그인하십시오.


Adil Sbai
Adil Sbai 2017년 5월 6일
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

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by