Counting occurrences of a pair of numbers in a logical vector
1 回表示 (過去 30 日間)
古いコメントを表示
What is an efficient way to count the number of occurrences of 1 in pairs in a logical vector and store in a cumulative summation output?
A = [0 1 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 ]; % Input vector
B = [0 1 1 1 1 0 0 0 0 0 2 2 0 0 3 3 3 ]; % Expected output
3 件のコメント
Image Analyst
2019 年 3 月 24 日
編集済み: Image Analyst
2019 年 3 月 24 日
Why do element 2 and 5, with two zeros between them, have 1 in the output, but elements 12 and 15, which also have two zeros between them not have 2's or 3's between them?
How far apart can two ones BE, and still be considered as a "pair"? Adjacent? One element apart (between them)? Two apart? Three?
To find starting indexes of pairs of adjacent 1's, use sprintf() and strfind():
A = [0 1 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 ] % Input vector
strA = sprintf('%d', A)
indexes = strfind(strA, '11')
dpb
2019 年 3 月 24 日
編集済み: dpb
2019 年 3 月 24 日
OP "paired up" the ones, IA, starting with the first occurrence they match in groups of two.
I rearranged his posting to make it easier to visualize.
This implies mod(sum(A==1),2) is zero for all A or if not there will be an end effect for the last that is undefined how to treat..
Looks to me that this one is just find(A) and then iterate through that list by twos...
採用された回答
dpb
2019 年 3 月 24 日
編集済み: dpb
2019 年 3 月 24 日
Mayhaps one can get more cleverer, but I'm all for just "git 'er done!"
ix=reshape(find(A),2,[]).';
B=zeros(size(A));
for i=1:size(ix,1)
B(ix(i,1):ix(i,2))=i;
end
As in earlier comment this does presume that A does always have matching pairs of ones...it will fail if numel(ix) is odd...
2 件のコメント
Image Analyst
2019 年 3 月 24 日
Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?
dpb
2019 年 3 月 24 日
Nah, the crystal ball came back from the shop (yet again)... :)
Actually, if you look at the input/output arrays in juxtaposition as rearranged, then it's not so difficult to pick out what OP actually did to get his result. With the two standing apart initially, I was also lost so I did that to see if I could find the pattern when side-by-side...and got lucky.
その他の回答 (1 件)
Jos (10584)
2019 年 3 月 24 日
A vectorised alternative:
A = [0 1 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 ]; % Input vector
ix = find(A)
ix = ix(2:2:end)
B = cumsum(A)
B(ix) = B(ix) - 1
B = (B+1)/2
B(B~=fix(B)) = 0
% [0 1 1 1 1 0 0 0 0 0 2 2 0 0 3 3 3]
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!