Asked by Lee
on 24 Mar 2019

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

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...

Image Analyst
on 24 Mar 2019

Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?

dpb
on 24 Mar 2019

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]

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## madhan ravi (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/452020-counting-occurrences-of-a-pair-of-numbers-in-a-logical-vector#comment_685017

## Image Analyst (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/452020-counting-occurrences-of-a-pair-of-numbers-in-a-logical-vector#comment_685037

## dpb (view profile)

Direct link to this comment:https://in.mathworks.com/matlabcentral/answers/452020-counting-occurrences-of-a-pair-of-numbers-in-a-logical-vector#comment_685055

Sign in to comment.