How would you loop through a vector and create new vectors (groups) based the condition of similar values per index

3 次查看(过去 30 天)
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

采纳的回答

Jean-Baptiste Lanfrey
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 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by