Filter löschen
Filter löschen

The number of consecutive ocurrances in an array

2 Ansichten (letzte 30 Tage)
reham elnabawy
reham elnabawy am 30 Apr. 2017
Kommentiert: Stephen23 am 1 Mai 2017
I have an array that is shown as: a=[0,0,1,1,1,0,0,1] and I would like to get the number of consecutive ocurrances in it along with the number itself meaning that I would like the output to be b=[2,0,3,1,2,0,1,1] where 0 occurred two consecutive times, 1 occurred three consecutive times, etc. Please help me and thank you in advance.
  3 Kommentare
John Chilleri
John Chilleri am 1 Mai 2017
The b is a description of vector a:
Two 0s, then three 1s, then two 0s, then one 1.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Guillaume
Guillaume am 1 Mai 2017
This is trivially achieved with diff and find:
a = [0, 0, 1, 1, 1, 0, 0, 1];
transitions = find(diff(a));
runlengths = diff([0, transitions, numel(a)]);
runvalues = a([transitions, end]);
valuelength = reshape([runlengths; runvalues], 1, [])

Kategorien

Mehr zu Elementary Math finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by