フィルターのクリア

How to count the number of consecutive numbers of the same value in an array

56 ビュー (過去 30 日間)
I have an array given as
x = [1 1 1 2 2 1 1 1]
I'd like to know a way I could go through each individual element in the array, and getting a value for how many steps the number stays at the same value. For instance, for this example, the output I would be looking for would be
y = [2 1 0 1 0 2 1 0]
Where the first value of 1 stays constant for another 2 steps, the second stays constant for one more step etc.

採用された回答

Jos (10584)
Jos (10584) 2014 年 2 月 24 日
% data
x = [1 1 1 2 2 1 1 1 3 3 3 3 3 5]
% engine
i = find(diff(x))
n = [i numel(x)] - [0 i]
c = arrayfun(@(X) X-1:-1:0, n , 'un',0)
y = cat(2,c{:})
  2 件のコメント
Gareth Pritchard
Gareth Pritchard 2014 年 2 月 24 日
Brilliant, thanks a lot!
Emil Jensen
Emil Jensen 2020 年 3 月 10 日
Briliant, tanjs r rot!

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2014 年 2 月 25 日
c = [1 1 1 2 2 1 1 1];
v = numel(c):-1:1;
ii = [true,diff(c)~=0];
n = v(ii);
t = [n(2:end)+1,1];
out = v - t(cumsum(ii));

Roger Stafford
Roger Stafford 2014 年 2 月 24 日
Here's a slightly different way:
x = [2 2 5 5 5 6 6 6 6 4 7 2 2 2];
n = size(x,2);
f = find([true,diff(x)~=0,true]);
y = zeros(1,n);
y(f(1:end-1)) = diff(f);
y = cumsum(y(1:n))-(1:n);
  1 件のコメント
Gareth Pritchard
Gareth Pritchard 2014 年 2 月 25 日
This also works great, thank you. Is there any way you could explain line by line what it is doing at all?

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by