How to find consecutive numbers

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

更多回答(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