function E = gsubadjmat(K,I)
% GSUBADJMAT Adjacency matrix for a subgrid
%
% E = GSUBADJMAT(K,I) where K is the node numbering and I is the
% list of nodes to include

    
% Jerod Weinman
% jerod@acm.org
  
%	$Id: gsubadjmat.m 1 2009-05-07 13:41:00Z weinman $
 
% Jerod Weinman
% jerod@acm.org
% Copyright 2004, 2008, 2009
 
%    This file is part of Matlab GridCRF.
%
%    Matlab GridCRF is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    Matlab GridCRF is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with Matlab GridCRF.  If not, see <http://www.gnu.org/licenses/>.
    
  if size(I,1)~=length(I)
	I = I';
  end;
  
  E = logical(sparse(length(I),length(I)));

  % Node inclusion indicator & number lookup
  A = sparse(K(end),1);
  A(I) = 1:length(I);

  %%%%%%%%%%%%%%%%%%%%
  % Horizontal edges
  % Only include edges that are connected to two included nodes
  
  E0 = mkrvector(K(:,1:end-1)); % left node list
  E1 = mkrvector(K(:,2:end)); % right node list
  
  Ie = find(A(E0) & A(E1));

  ndx = sub2ind(size(E),full(A(E0(Ie))),full(A(E1(Ie))));
  E(ndx) = 1;
  
  %%%%%%%%%%%%%%%%%%%%
  % Vertical edges
  E0 = mkrvector(K(1:end-1,:));
  E1 = mkrvector(K(2:end,:));

  Ie = find(A(E0) & A(E1));
  
  ndx = sub2ind(size(E),full(A(E0(Ie))),full(A(E1(Ie))));
  E(ndx) = 1;
