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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Jean-Baptiste Lanfrey
Jean-Baptiste Lanfrey am 12 Apr. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by