问题描述:

I have an array in MATLAB containing elements such as

A=[12 13 14 15 30 31 32 33 58 59 60];

How can I identify breaks in values of data? For example, the above data exhibits breaks at elements 15 and 33. The elements are arranged in ascending order and have an increment of one. How can I identify the location of breaks of this pattern in an array? I have achieved this using a for and if statement (code below). Is there a better method to do so?

count=0;

for i=1:numel(A)-1

if(A(i+1)==A(i)+1)

continue;

else

count=count+1;

q(count)=i;

end

end

网友答案:

Good time to use diff and find those neighbouring differences that aren't equal to 1. However, this will return an array which is one less than the length of your input array because it finds pairwise differences up until the last element, so naturally there will be one less. As such, when you find the locations that aren't equal to 1, make sure you add 1 to the locations to account for this:

>> A=[12 13 14 15 30 31 32 33 58 59 60];
>> q = find(diff(A) ~= 1) + 1

q =

     5     9

This tells us that locations 5 and 9 in your array is where the jump happens, and that's right for your example data.

However, if you want to find the locations before the jump happens, such as in your code, don't add 1 to the result:

>> q = find(diff(A) ~= 1)

q =

     4     8
相关阅读:
Top