Counting occurrences of a pair of numbers in a logical vector
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Image Analyst
am 24 Mär. 2019
Bearbeitet: Image Analyst
am 24 Mär. 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
am 24 Mär. 2019
Bearbeitet: dpb
am 24 Mär. 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...
Akzeptierte Antwort
dpb
am 24 Mär. 2019
Bearbeitet: dpb
am 24 Mär. 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 Kommentare
Image Analyst
am 24 Mär. 2019
Say, did you get a copy of the Mind Reading Toolbox with R2019a like Walter did?
dpb
am 24 Mär. 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.
Weitere Antworten (1)
Jos (10584)
am 24 Mär. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!