Counting occurrences of a pair of numbers in a logical vector

1 vue (au cours des 30 derniers jours)
Lee
Lee le 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
  3 commentaires
Image Analyst
Image Analyst le 24 Mar 2019
Modifié(e) : Image Analyst le 24 Mar 2019
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 le 24 Mar 2019
Modifié(e) : dpb le 24 Mar 2019
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...

Connectez-vous pour commenter.

Réponse acceptée

dpb
dpb le 24 Mar 2019
Modifié(e) : dpb le 24 Mar 2019
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 commentaires
Image Analyst
Image Analyst le 24 Mar 2019
Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?
dpb
dpb le 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.

Connectez-vous pour commenter.

Plus de réponses (1)

Jos (10584)
Jos (10584) le 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]

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by