MATLAB Answers

Lee
0

Counting occurrences of a pair of numbers in a logical vector

Asked by Lee
on 24 Mar 2019
Latest activity Answered by Jos (10584)
on 24 Mar 2019
Accepted Answer by dpb
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 Comments

You say in pairs but why the first resultant is 1 1 1 1 ? You didn't explain the pattern at all after someone answers you will completely ask a different question then.
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')
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...

Sign in to comment.

2 Answers

Answer by dpb
on 24 Mar 2019
Edited by dpb
on 24 Mar 2019
 Accepted Answer

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 Comments

Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?
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.

Sign in to comment.


Answer by Jos (10584)
on 24 Mar 2019

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 Comments

Sign in to comment.