Daniel@0: function G = mk_2D_lattice(nrows, ncols, con) Daniel@0: % MK_2D_LATTICE Return adjacency matrix for nearest neighbor connected 2D lattice Daniel@0: % G = mk_2D_lattice(nrows, ncols, con) Daniel@0: % G(k1, k2) = 1 iff k1=(i1,j1) is a neighbor of k2=(i2,j2) Daniel@0: % (Two pixels are neighbors if their Euclidean distance is less than r.) Daniel@0: % Default connectivity = 4. Daniel@0: % Daniel@0: % WE ASSUME NO WRAP AROUND. Daniel@0: % Daniel@0: % This is the neighborhood as a function of con: Daniel@0: % Daniel@0: % con=4,r=1 con=8,r=sqrt(2) con=12,r=2 con=24,r=sqrt(8) Daniel@0: % nn 2nd order 4th order Daniel@0: % x x x x x x Daniel@0: % x x x x x x x x x x x x Daniel@0: % x o x x o x x x o x x x x o x x Daniel@0: % x x x x x x x x x x x x Daniel@0: % x x x x x x Daniel@0: % Daniel@0: % Examples: Daniel@0: % Consider a 3x4 grid Daniel@0: % 1 4 7 10 Daniel@0: % 2 5 8 11 Daniel@0: % 3 6 9 12 Daniel@0: % Daniel@0: % 4-connected: Daniel@0: % G=mk_2D_lattice(3,4,4); Daniel@0: % find(G(1,:)) = [2 4] Daniel@0: % find(G(5,:)) = [2 4 6 8] Daniel@0: % Daniel@0: % 8-connected: Daniel@0: % G=mk_2D_lattice(3,4,8); Daniel@0: % find(G(1,:)) = [2 4 5] Daniel@0: % find(G(5,:)) = [1 2 3 4 6 7 8 9] Daniel@0: Daniel@0: % meshgrid trick due to Temu Gautama (temu@neuro.kuleuven.ac.be) Daniel@0: Daniel@0: if nargin < 3, con = 4; end Daniel@0: Daniel@0: switch con, Daniel@0: case 4, r = 1; Daniel@0: case 8, r = sqrt(2); Daniel@0: case 12, r = 2; Daniel@0: case 24, r = sqrt(8); Daniel@0: otherwise, error(['unrecognized connectivity ' num2str(con)]) Daniel@0: end Daniel@0: Daniel@0: Daniel@0: npixels = nrows*ncols; Daniel@0: Daniel@0: [x y]=meshgrid(1:ncols, 1:nrows); Daniel@0: M = [x(:) y(:)]; Daniel@0: M1 = repmat(reshape(M',[1 2 npixels]),[npixels 1 1]); Daniel@0: M2 = repmat(M,[1 1 npixels]); Daniel@0: %D = squeeze(sum(abs(M1-M2),2)); % Manhattan distance Daniel@0: M3 = M1-M2; Daniel@0: D = sqrt(squeeze(M3(:,1,:)) .^2 + squeeze(M3(:,2,:)) .^2); % Euclidean distance Daniel@0: G = reshape(D <= r,npixels,npixels); Daniel@0: G = setdiag(G, 0);