1

MATLAB の論理配列内のすべての一連の 1 と 0 の長さを見つけたいです。これは私がしたことです:

A = logical([0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1]);
%// Find series of ones:
csA = cumsum(A);
csOnes = csA(diff([A 0]) == -1);
seriesOnes = [csOnes(1) diff(csOnes)];
%// Find series of zeros (same way, using ~A)
csNegA = sumsum(~A);
csZeros = csNegA(diff([~A 0]) == -1);
seriesZeros = [csZeros(1) diff(csZeros)];

これは機能し、 と を与えseriesOnes = [4 2 5]ますseriesZeros = [3 1 6]。しかし、私の意見ではかなり醜いです。

これを行うためのより良い方法があるかどうか知りたいです。これは安価であるため、パフォーマンスは問題にAなりません (要素数が数千以下)。コードの明快さと優雅さを求めています。

これ以上何もできない場合は、これを小さなヘルパー関数に入れるだけで、見る必要がなくなります。

4

3 に答える 3

1

これを試すことができます:

A = logical([0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 1]);
B = [~A(1) A ~A(end)];                %// Add edges at start/end
edges_indexes = find(diff(B));        %// find edges
lengths = diff(edges_indexes);        %// length between edges

%// Separate zeros and ones, to a cell array
s(1+A(1)) = {lengths(1:2:end)};
s(1+~A(1)) = {lengths(2:2:end)};
于 2015-03-01T11:18:00.683 に答える
0

このstrfind(数値配列と文字列配列でうまく機能します)ベースのアプローチは、従うのが簡単になる可能性があります-

%// Find start and stop indices for ones and zeros with strfind by using
%// "opposite (0 for 1 and 1 for 0) sentients" 
start_ones = strfind([0 A],[0 1]) %// 0 is the sentient here and so on
start_zeros = strfind([1 A],[1 0])
stop_ones = strfind([A 0],[1 0])
stop_zeros = strfind([A 1],[0 1])

%// Get lengths of islands of ones and zeros using those start-stop indices 
length_ones = stop_ones - start_ones + 1
length_zeros = stop_zeros - start_zeros + 1
于 2015-03-01T09:14:05.537 に答える