MATLAB: Distribution of consecutive numbers

find

Hi ,
I have a column of 9 states (attached the file) . How can I know in this column how many times each state is followed by another state? in other words, the values ranges between 1 and 9. how can i know how many times 1 is followed by 1, 1 followed by 2, …1 followed by 9 (the same goes for each state)?

Best Answer

I don't think there's a way t do that without a loop (either explicit or with arrayfun).
%build list of patterns to search:
[n1, n2] = ndgrid(1:9);
patterns = [n1(:), n2(:)];
%search for each pattern with a loop:
x1 = reshape(x1, 1, []); %need a row vector
count = zeros(size(patterns, 1), 1);
for row = 1:size(patterns, 1)
count(row) = numel(strfind(x1, patterns(row, :))); %despite its name strfind can be used to find patterns of numbers
end
%pretty display

table(patterns, count)
edit: actually I was completely wrong, it can easily be done without a loop, but temporarily requires much more memory:
[n1, n2] = ndgrid(1:9);
patterns = [n1(:), n2(:)];
%count of pattern
transitions = permute([x1(1:end-1), x1(2:end)], [3 2 1]);
count = sum(all(patterns == transitions, 2), 3)
%pretty display
table(patterns, count)
edit again: Another option is to build the graph of the transitions and use the edgecount function:
g = graph(x1(1:end-1), x1(2:end));
[n1, n2] = ndgrid(1:9);
count = edgecount(g, n1(:), n2(:));
patterns = [n1(:), n2(:)];
table(patterns, count)