# How do I count how many times in a row a value occurs?

16 visualizzazioni (ultimi 30 giorni)
David Haydock il 17 Mag 2022
Modificato: Torsten il 17 Mag 2022
If I have some list, say:
A = [1 2 4 3 1 1 1 1];
How do I calculate and store *how many times in a row* each number occurs?
For example, for the value 1, I would want an output of [1, 4], since it appears one time, then when it appears again in the list it repeats four times.
Any help would be appreciated.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Monica Roberts il 17 Mag 2022
Probably not the fastest/cleanest but this should work. Assuming that A contains at least one value.
ind = find(A==1);
count = 1;
for i = 1:numel(ind)-1
d = ind(i+1)-ind(i);
if d == 1
count = count+1;
else
count = 1;
end
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Più risposte (1)

Torsten il 17 Mag 2022
Modificato: Torsten il 17 Mag 2022
A = [1 2 4 3 1 1 1 1];
Au = unique(A);
count = arrayfun(@(i)numel(find(A==Au(i))),1:numel(Au))
output = [Au;count].'
Your question is unclear since the 1 appears 5 times in the row. If you want the maximum number of subsequent repetitions of a number or something similar, you should again formulate your question properly.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrices and Arrays 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!

Translated by