How would you loop through a vector and create new vectors (groups) based the condition of similar values per index
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Matter_n_Energy
il 12 Apr 2022
Risposto: Jean-Baptiste Lanfrey
il 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 Commenti
Risposta accettata
Jean-Baptiste Lanfrey
il 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!