# How can I count the followed occurrences of each element in a vector in MATLAB?

2 views (last 30 days)
lamghari on 30 Nov 2015
Commented: lamghari on 30 Nov 2015
Hi, I want to count the number of followed occurrences of each element in a vector.
So if my input is
x = [1 1 1 2 2 1 1 2 5 5]
I need an output
y = [1 2 1 2 5;3 2 2 1 2] How do I do this?
##### 2 CommentsShowHide 1 older comment
lamghari on 30 Nov 2015
thank's William But this post concerns the consecutive numbers (x + 1) !! I need the occurrence of the same numbers followed

Sign in to comment.

### Accepted Answer

Stephen23 on 30 Nov 2015
Edited: Stephen23 on 30 Nov 2015
Judicious use of diff solves this easily:
x = [1 1 1 2 2 1 1 2 5 5];
f = [find(diff(x)),numel(x)];
y(2,:) = [f(1),diff(f)];
y(1,:) = x(f);
which generates this output:
>> y =
1 2 1 2 5
3 2 2 1 2
##### 4 CommentsShowHide 3 older comments
lamghari on 30 Nov 2015
thanks a lot for your cooperation :)

Sign in to comment.

### More Answers (1)

Jan on 30 Nov 2015
If run time matters, you can try FEX: RunLength
x = [1 1 1 2 2 1 1 2 5 5];
[b, n] = RunLength(x);
Result = [b; n];
##### 1 CommentShowHide None
lamghari on 30 Nov 2015
Thank you Jan

Sign in to comment.

### Categories

Find more on Logical in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by