EDIT: @Amro provided a much better solution (well, which is better in the vast majority of cases, I suspect that my method will work better if MaxX very large and X contains zeros - this is because the presence of zeros precludes the use of sparse and the big MaxX slows down the accumarray approach as it creates a MaxX matrix from MaxX).
EDIT: Thanks to @EitanT for specifying the improvement that can be made with accumarray .
Here is how I would decide:
%Generate some random data T = 20; MaxX = 3; X = randi(MaxX, T, 1); %Get the unique combinations and an index. Note, I am assuming X is a column vector. [UniqueComb, ~, Ind] = unique([X(1:end-1), X(2:end)], 'rows'); NumComb = size(UniqueComb, 1); %Count the number of occurrences of each combination Count = accumarray(Ind, 1);
All unique consecutive combinations of two elements are now stored in UniqueComb , and the corresponding counts for each unique combination are stored in Count .
source share