Group consecutive and non-consecutive values in a vector

5 ビュー (過去 30 日間)
Daniel van Huyssteen
Daniel van Huyssteen 2022 年 3 月 7 日
コメント済み: Raymond MacNeil 2024 年 2 月 3 日
Consider a vector V2 containing certain entries of some other larger vector V1 comprising nV1 entries.
How would one split up the vector V2 into segments comprising consecutive entries and output these segments as the cells of a cell array C?
Additionally, it could be the case that V2 'wraps', that is, if the first segment of C contains the value 1, and the last segment of C contains the value nV1, these two segments should be merged.
I would like to avoid dynamic re-sizing of vectors/arrays if possible.
Possible test case #1:
Input:
nV1 = 8;
V2 = [1];
Output:
C = {[1]};
Possible test case #2:
Input:
nV1 = 8;
V2 = [3,4,5];
Output:
C = {[3,4,5]};
Possible test case #3:
Input:
nV1 = 8;
V2 = [1,2,4,6,7];
Output:
C = {{[1,2]},{[4]},{[6,7]}};
Possible test case #4:
Input:
nV1 = 8;
V2 = [1,2,4,7,8];
Output:
C = {{[1,2,7,8]},{[4]}};
or
C = {{[4]},{[1,2,7,8]}};
  1 件のコメント
Jan
Jan 2022 年 3 月 7 日
I assume you do not need a nested cell
C = {{[4]},{[1,2,7,8]}}
but a cell is sufficient:
C = {[4], [1,2,7,8]}

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

採用された回答

Jan
Jan 2022 年 3 月 7 日
編集済み: Jan 2022 年 11 月 17 日
nV1 = 8;
V2 = [1,2,4,6,7];
grp = cumsum([true, diff(V2)~=1]);
C = splitapply(@(x) {x}, V2, grp);
if V2(end) == nV1
C{1} = [C{1}, C{end}];
C(end) = [];
end
C
C = 1×3 cell array
{[1 2]} {[4]} {[6 7]}
  2 件のコメント
Hyeongseok
Hyeongseok 2022 年 11 月 17 日
Nice solution! Thanks!
Raymond MacNeil
Raymond MacNeil 2024 年 2 月 3 日
Brilliant, thanks.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by