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

50 vues (au cours des 30 derniers jours)
丈太郎 森川
丈太郎 森川 le 20 Mai 2021
例えば、
[0]と[1]の配列
[0 0 0 1 1 1 0 0 1]
連続した数字をカウントアップする方法を教えていただけないでしょうか。
連続が途切れた場合は1に戻る。
上の例ですと
[1 2 3 1 2 3 1 2 1]

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!