4

I have vector with values between 1 and N > 1. Some values COULD occur multiple times consecutively. Now I want to have a second row which counts the consecutively entries and remove all those consecutively occuring entries, e.g.:

A = [1 2 1 1 3 2 4 4 1 1 1 2]'

would lead to:

B = [1 1;
     2 1;
     1 2;
     3 1;
     2 1;
     4 2;
     1 3;
     2 1]

(you see, the second column contains the number of consecutively entries! I came across accumarray() in MATLAB recently but I can't find any solution with it for this task since it always regards the whole vector and not only consecutively entries.

Any idea?

4

2 に答える 2

5

これはおそらく最も読みやすくエレガントな方法ではありませんが、大きなベクトルがあり、速度が問題になる場合は、このベクトル化が役立つ場合があります...

A = [1 2 1 1 3 2 4 4 1 1 1 2];

最初に、先頭と末尾のゼロで A をパディングして、最初と最後の遷移をキャプチャします。

>>  A = [0, A, 0];

隣接する値の差がゼロに等しくない遷移位置を見つけることができます。

>> locations = find(diff(A)~=0);

しかし、A の先頭をゼロでパディングしたため、最初の遷移は意味がなく、2:end からの位置のみを取得します。これらの A の値は、各セグメントの値です。

>> first_column = A(locations(2:end))

ans =

     1     2     1     3     2     4     1     2

これが最初の列です。各数値のカウントを見つけます。これは、位置の違いからわかります。ここで、両端のパディング A が重要になります。

>> second_column = diff(locations)

ans =

 1     1     2     1     1     2     3     1

最後に組み合わせる:

B = [first_column', second_column']

B =

 1     1
 2     1
 1     2
 3     1
 2     1
 4     2
 1     3
 2     1

これはすべて、読みにくい 1 行にまとめることができます。

>> A = [1 2 1 1 3 2 4 4 1 1 1 2]';
>> B = [A(find(diff([A; 0]) ~= 0)), diff(find(diff([0; A; 0])))]

B =

 1     1
 2     1
 1     2
 3     1
 2     1
 4     2
 1     3
 2     1
于 2012-01-20T13:49:27.833 に答える
2

データセットをループする別の方法はわかりませんが、かなり簡単です。おそらくこれは最もエレガントなソリューションではないかもしれませんが、私が見る限り、うまく機能します。

function B = accum_data_set(A)
    prev = A(1);
    count = 1;
    B = [];
    for i=2:length(A)
        if (prev == A(i))
            count = count + 1;
        else
            B = [B;prev count];
            count = 1;
        end
        prev = A(i);
    end
    B = [B;prev count];

出力:

>> A = [1 2 1 1 3 2 4 4 1 1 1 2]';
>> B = accum_data_set(A)

B =

     1     1
     2     1
     1     2
     3     1
     2     1
     4     2
     1     3
     2     1
于 2012-01-20T13:39:56.710 に答える