Create vector only containing consecutive numbers of other vector

2 ビュー (過去 30 日間)
Janina Koussev
Janina Koussev 2015 年 3 月 30 日
コメント済み: Star Strider 2015 年 3 月 31 日
Hi, I'm searching for a possibility to build a vector B which only contains the consecutive numbers of vector A. I tried it like this but it is not working. Can someone help me?
A=[2 5 6 7]; B=0; for m=1:length(A)-1 if diff(A)==1 B=A(m); m=m+1; end end
The anwser should look like this: B=[5 6 7]

採用された回答

Guillaume
Guillaume 2015 年 3 月 30 日
編集済み: Guillaume 2015 年 3 月 30 日
Using just diff and logical operations (no find):
A = [2 5 6 7 10 12 13 20];
dA = diff(A) == 1;
B = A([0 dA] | [dA 0])
This assumes that A is a row vector.
  1 件のコメント
Janina Koussev
Janina Koussev 2015 年 3 月 30 日
In my data A was a column vector... Thanks a lot!

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 3 月 30 日
For large vectors using logical indexing will probably be faster than using find:
>> A = [2,5,6,7];
>> X = diff(A)==1;
>> Y = [false,X] | [X,false];
>> A(Y)
ans =
5 6 7
  6 件のコメント
Stephen23
Stephen23 2015 年 3 月 31 日
編集済み: Stephen23 2015 年 3 月 31 日
@Janina Koussev: Ask this in a new question.
Star Strider
Star Strider 2015 年 3 月 31 日
I delete my Answers if they are neither Accepted nor Voted. Many others do as well.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by