How to filter an array?

7 ビュー (過去 30 日間)
Meshooo
Meshooo 2016 年 1 月 6 日
コメント済み: Guillaume 2016 年 1 月 7 日
Dear all,
I have this array
A = [0;0;0;0;0;0;1;1;1;0;0;0;0;0;0;1;0;0;0;0];
I want only one representative for each group of ones. So how to make
A = [0;0;0;0;0;0;0;1;0;0;0;0;0;0;0;1;0;0;0;0];
Any help will be appreciated.
Best, Meshoo
  3 件のコメント
Stephen23
Stephen23 2016 年 1 月 6 日
And what if there are an even number of ones?
A = [0;1;1;0]
what output do you want?
Meshooo
Meshooo 2016 年 1 月 6 日
I don't care which right or left to take in case of even number of ones.
A = [0;0;1;0]
or
A = [0;1;0;0]
Any answer is OK.

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

採用された回答

Guillaume
Guillaume 2016 年 1 月 6 日
It's very simple:
diff([0; A]) == 1
simply detects all transition from 0 to 1 and return them as 1.
  1 件のコメント
Guillaume
Guillaume 2016 年 1 月 7 日
Note that this keeps just the first 1 of a block as opposed to the middle 1 of a block, which the other solutions do.

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

その他の回答 (3 件)

goerk
goerk 2016 年 1 月 6 日
A = [0;0;0;0;0;0;1;1;1;0;0;0;0;0;0;1;0;0;0;0];
% A = [0;1;1;0;1;1;1];
dA = diff(A);
ind = 1:length(A);
startInds = ind(dA>0)+1;
endInds = ind(dA<0);
if length(endInds)<length(startInds) %last value is 1
endInds(end+1) = length(A);
end
midInd = floor((startInds+endInds)/2); % when even choose left
% midInd = ceil((startInds+endInds)/2); % when even choose right
B = zeros(size(A));
B(midInd) = 1;
[A B] % show result, to check input and output
  2 件のコメント
Guillaume
Guillaume 2016 年 1 月 6 日
Your answer will fail if the first element of A is 1. And if it starts and ends with 1, the start and end offsets will be completely wrong due to the way you detect that the last value is 1.
The best way to solve both is to prepend and append A with 0 before the diff:
dA = diff([0 A 0]); %guarantees you have the same number of starts and ends.
midInd = floor((find(dA > 0) + find(dA < 0) - 1) / 2); %much simpler way of calculating mid indices
goerk
goerk 2016 年 1 月 6 日
You are right, for a 1 at the first position my will fail. Thanks for your very nice and short solution. With the correct concatenation it works fine.
dA = diff([0; A; 0]);

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


Stephen23
Stephen23 2016 年 1 月 6 日
>> A = [0;0;0;0;0;0;1;1;1;0;0;0;0;0;0;1;0;0;0;0];
>> X = find(diff([0;A;0]));
>> Z = zeros(size(A));
>> Z(fix((X(1:2:end)+X(2:2:end)-1)/2)) = 1
Z =
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1
0
0
0
0

Meshooo
Meshooo 2016 年 1 月 7 日
Thank you all for the kind help and suggestions.

カテゴリ

Help Center および File ExchangeFrequency Transformations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by