How to count the number of times that values changes?

21 views (last 30 days)
Mia Dier
Mia Dier on 9 Jan 2021
Commented: Mario Malic on 9 Jan 2021
A=[1 1 1 2 1 3 3 1 1]' I want to get:
B=[NaN 0 0 1 2 3 3 4 4]'
The second and third values of B are 0 because A doesn't change value. Fourth value is 1 because A changes value. Fifth value is 2 because A changes value again. And so on...

Accepted Answer

Stephen23
Stephen23 on 9 Jan 2021
Edited: Stephen23 on 9 Jan 2021
A = [1;1;1;2;1;3;3;1;1]
A = 9×1
1 1 1 2 1 3 3 1 1
B = [NaN;cumsum(diff(A)~=0)]
B = 9×1
NaN 0 0 1 2 3 3 4 4

More Answers (1)

Mario Malic
Mario Malic on 9 Jan 2021
Edited: Mario Malic on 9 Jan 2021
Hello,
This should do the trick.
B = [NaN; cumsum(diff(A) ~= 0)]';
  2 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by