0001 function w = firstinrow(G, v)
0002 % FIRSTINROW : First nonzero in row / lowest out-neighbor.
0003 %
0004 % w = firstinrow(G): G is a graph or sparse matrix.
0005 %                    w(v) is the lowest numbered out-neighbor of vertex v,
0006 %                         that is, the first nonzero column in row v of G.
0007 %                    w(v) = 0 if row v is empty.
0008 %
0009 % w = firstinrow(G,v)  returns only the scalar w(v).
0010 %
0011 % Pre-prototype version of 8 Sep 2005.  JRG, SPR
0012 
0013 % Strip the input down to a sparse adjacency matrix
0014 if isstruct(G)
0015     G = G.edgeWeights;
0016 end;
0017 if iscell(G)
0018     G = G{1};
0019 end;
0020 
0021 if nargin > 1
0022     % return scalar for row v
0023     w = min(find(G(v,:)));
0024     if isempty(w)
0025         w = 0;
0026     end;
0027 else
0028     % return column vector, one entry per row
0029     [nr,nc] = size(G);
0030     [I,J,V] = find(G);
0031     H = sparse(J,I,nc+1-J,nc,nr);
0032     w = full(max(H))';
0033     f = find(w);
0034     w(f) = nc+1-w(f);
0035 end;