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)
Ältere Kommentare anzeigen
Matter_n_Energy
am 12 Apr. 2022
Beantwortet: Jean-Baptiste Lanfrey
am 12 Apr. 2022
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 Kommentare
Akzeptierte Antwort
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
0 Kommentare
Weitere Antworten (0)
Siehe auch
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!