Counting occurrences of a pair of numbers in a logical vector

조회 수: 1 (최근 30일)
Lee
Lee 2019년 3월 24일
답변: Jos (10584) 2019년 3월 24일
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
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
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
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
Image Analyst 2019년 3월 24일
Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?
dpb
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)
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]

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by