How would you loop through a vector and create new vectors (groups) based the condition of similar values per index
1 回表示 (過去 30 日間)
古いコメントを表示
Matter_n_Energy
2022 年 4 月 12 日
回答済み: Jean-Baptiste Lanfrey
2022 年 4 月 12 日
Given an input vector
nums = [1 2 3 1 3 3 1 2 2 3 2 1 3];
I'd like to loop through and create groups such that when an element is repeated, everything before it is a group (new vector). For example, using the vector above, the groups would be:
[1 2 3] [1 3] [3 1 2] [2 3] [2 1 3]
To elaborate, the first group stops at 3 because everthing is unique until that second 1 is reached because it's a repeat of index 1. Then the second group starts at that index for the second 1, reads through and sees that 3 repeats, so everything from that second 1 to the next 3 is a group. Then it starts at the next index...
Basically each group needs to have non-repeating values.
Thanks in advance
0 件のコメント
採用された回答
Jean-Baptiste Lanfrey
2022 年 4 月 12 日
Something like this should work.
nums = [1 2 3 1 3 3 1 2 2 3 2 1 3];
groups{1} = nums(1);
for number = nums(2:end)
if any(groups{end}-number==0)
groups{end+1} = number;
else
groups{end} = [groups{end} number];
end
end
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!