Find the first and last elements of consecutive values in a vector

21 次查看(过去 30 天)
Let's say we have an arbitrary vector like this with ascending values:
a= [10 11 12 19 21 25 29 30 31 32 33 39 50];
and we want to find the first and last element of each consecutive (integer) values. The answer could be in this form:
First consecutive values: [10 11 12]
Second consecutive values: [29 30 31 32 33]
CI_f = [10 29]
CI_l = [12 33]
How could we do it in MATLAB without loop?
Is it also possible to put a condition for the length of the consecutive values to be between specific numbers of values, let's say between 3 and 8?
Thanks in advance for helping :)

采纳的回答

Stephen23
Stephen23 2018-3-27
编辑:Stephen23 2018-3-27
It is easy to identify the first and last elements of consecutive sequences of values:
>> a = [10 11 12 19 21 25 29 30 31 32 33 39 50];
>> D = diff([0,diff(a)==1,0]);
>> first = a(D>0)
first =
10 29
>> last = a(D<0)
last =
12 33
"Is it also possible to put a condition for the length of the consecutive values to be between specific numbers of values, let's say between 3 and 8?"
Yes. Add find and experiment with the differences:
1 + find(D<0) - find(D>0)
Hint: compare against the require limits to generate an index.

更多回答(1 个)

Pawel Jastrzebski
Pawel Jastrzebski 2018-3-27
As to what you put as an answer, it can be coded this way:
CI_f = [CI{1}(1) CI{2}(1)]
CI_l = [CI{1}(end) CI{2}(end)]
And the output is going to be the same:
>> CI_f
CI_f =
10 30
>> CI_l
CI_l =
12 33
However I find it your question completely unclear.
  • You've got a vector 'a' consisting of 13 elements.
  • Values from that vector are used to create the cell arrays
  • 1st cell array CI{1} holds 3 elements which are consecutive vales of 'a': indices 1 to 3
  • 2nd cell array CI{2} holds 4 elements which are consecutive vales of 'a': indices 8 to 11
  • Where's the pattern here?
  • Are there going to be more cell arrays? I.e. CI{3} holding 5 elements of 'a': what indices??
  • What are you trying to achieve?
  • Why CI's are stored as cells? What's wrong with the row vectors?
  4 个评论
RZM
RZM 2018-3-27
编辑:RZM 2018-3-27
Thanks but this is still not what I meant. If we start reading "a" from left to right as we normally do, CI_1 is the first sequence of consecutive numbers. The next sequence of consecutive values in "a" is 29 to 33 so the CI_2 is [29 30 31 32 33]. There is no other rule in creation of "a" despite it has to have ascending integer values with growing indices and a sequence here refers to the consecutive ascending values with the difference of "one".

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by