I have matrix R in which each element is integer of range [0 7]. I want to calculate the count of neighbor, let say for pixel value 0 how many times it has the neighbor 1, 2, ..., 7. every pixel has eight neighbors, for example
[n1 n2 n3 n4 x n5 n6 n7 n8]
where pixel x have eight neighbors. As a resultant I think we will have an other matrix of 8 x 8, or we can say 8 histograms as we have eight possible values in given matrix R.
I hope I have explained what I want :-(
If you don't have the image processing toolbox, or if you want your code to be useful to those who don't, this is just as fast. Note that the example only looks for the neighbors of the number 7. You can put this into a loop as needed. I assume your matrix is named x.
H = single(x==7); H = logical(conv2(H,ones(3),'same'))~=H; H = x(H(:)); Y = unique(H); H = histc(H,Y); H = [Y H];
I would take an image processing approach:
x = zeros(5); %sample matrix x(3:5,3:5) = [1 2 1;1 7 2;3 4 1]; x(5) = 7;
BW = x==7; %We'll count neighbors of 7s M = xor(imdilate(BW,ones(3)),BW); %neighbors of 7s uv = unique(x(M)); %unique neighbors n = histc(x(M),uv); %count unique neighbors [uv n] %display number of unique values to occurences
A = randi([0 7],10);
A1 = nan(size(A)+2); A1(2:end-1,2:end-1) = A; k = (0:7)'; n = numel(k); out = zeros(n); d = true(3); d(5) = false; for i1 = 1:n [ii,jj] = find(A1 == k(i1)); p = zeros(n,1); for i2 = 1:numel(ii) q = A1(ii(i2) + (-1:1),jj(i2) + (-1:1)); p = p + histc(q(d&(~isnan(q))),k); end out(:,i1) = p; end
variant based on the idea of Sean and Matt:
k = (0:7)'; out = zeros(numel(k)); for a = 1:numel(k) out(:,a) = histc(x(bwdist(x == k(a),'chessboard') == 1),k); end