How do I extract consecutive numbers from a matrix?

3 ビュー (過去 30 日間)
Simo
Simo 2014 年 6 月 24 日
コメント済み: Carlene Horner 2019 年 6 月 18 日
I have a matrix like: A=[1 2 5 6 7 8 9 20 21 22 23…] I'd like to separate consecutive number, like: C=[1 2] D=[5 6 7 8 9], E=[ 20 21 22 23]

採用された回答

Cedric
Cedric 2014 年 6 月 24 日
編集済み: Cedric 2014 年 6 月 24 日
Here is a solution, but there are many ways to do it, some simpler than others:
grouped = mat2cell( A, 1, diff( [0, find(diff(A) ~= 1), length(A)] )) ;
where grouped is a cell array with the following content
>> grouped{1}
ans =
1 2
>> grouped{2}
ans =
5 6 7 8 9
>> grouped{3}
ans =
20 21 22 23
Edit : here is a funny way for Star Strider, who wanted a tutorial about ACCUMARRAY ;-)
grouped = accumarray( cumsum([1, diff(A) ~= 1]).', A, [], @(x){x} ) ;
  3 件のコメント
Cedric
Cedric 2014 年 6 月 24 日
I was actually unaware that ACCUMARRAY could output cell arrays until I learned that from one of Andrei's solutions that blew my mind away.
Carlene Horner
Carlene Horner 2019 年 6 月 18 日
I keep getting a horzcat error. I'm assuming this is because when finding the difference of a vector, the length of that difference vector is one less of the original vector. How do you fix this? Thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by