連続した同じ数字をカウントアップする方法

例えば、
[0]と[1]の配列
[0 0 0 1 1 1 0 0 1]
連続した数字をカウントアップする方法を教えていただけないでしょうか。
連続が途切れた場合は1に戻る。
上の例ですと
[1 2 3 1 2 3 1 2 1]

 采纳的回答

Atsushi Ueno
Atsushi Ueno 2021-5-20

2 个投票

x = [0 0 0 1 1 1 0 0 1] ;
y = cell2mat(arrayfun(@(t)1:t,diff(find([1 diff(x) 1])),'un',0));
演算の過程をメモします
x = [0 0 0 1 1 1 0 0 1] ;
>> diff(x)
ans = 0 0 1 0 0 -1 0 1
>> find([1 diff(x) 1])
ans = 1 4 7 9 10
>> diff(find([1 diff(x) 1]))
ans = 3 3 2 1
>> arrayfun(@(t)1:t,diff(find([1 diff(x) 1])),'un',0)
ans = {[1,2,3], [1,2,3], [1,2], 1}
>> cell2mat(arrayfun(@(t)1:t,diff(find([1 diff(x) 1])),'un',0))
ans = 1 2 3 1 2 3 1 2 1
1や0以外の数値でも機能します。なんと1行です。天才的発想ですね。もちろん私が考えたものではなく、Codyのある問題に対する回答なのでリンク掲載は控えます。(日本人は検索で辿り着いてしまうかもしれませんが)

2 个评论

Atsushi Ueno
Atsushi Ueno 2021-5-20
(このコメントは意図的に英語の記述を避けています)
キーワード:「ランレングスエンコーダ」というキーワードで検索すると様々な言語によるエンコード方法の実装が見つかります。マトラボのファイルエクスチェンジでも見つかりますよ。
丈太郎 森川
丈太郎 森川 2021-5-20
早速のご回答ありがとうございます!
大変助かりますm(_ _)m

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Timing and presenting 2D and 3D stimuli 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!