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

1 回表示 (過去 30 日間)
lamghari
lamghari 2015 年 11 月 30 日
コメント済み: lamghari 2015 年 11 月 30 日
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 件のコメント
lamghari
lamghari 2015 年 11 月 30 日
thank's William But this post concerns the consecutive numbers (x + 1) !! I need the occurrence of the same numbers followed

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2015 年 11 月 30 日
編集済み: Stephen23 2015 年 11 月 30 日
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 件のコメント
Stephen23
Stephen23 2015 年 11 月 30 日
編集済み: Stephen23 2015 年 11 月 30 日
If you have a newer MATLAB version, you can use repelem, which provides exactly this functionality:
repelem(A(1,:),A(2,:))
Otherwise use arrayfun and repmat:
>> A = [1,2,1,2,5; 3,2,2,1,2];
>> C = arrayfun(@(v,n)repmat(v,1,n),A(1,:),A(2,:),'UniformOutput',false);
>> B = horzcat(C{:})
B =
1 1 1 2 2 1 1 2 5 5
lamghari
lamghari 2015 年 11 月 30 日
thanks a lot for your cooperation :)

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2015 年 11 月 30 日
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];

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by