reachdist.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function [R,D] = reachdist(CIJ)
  2. %REACHDIST Reachability and distance matrices
  3. %
  4. % [R,D] = reachdist(CIJ);
  5. %
  6. % The binary reachability matrix describes reachability between all pairs
  7. % of nodes. An entry (u,v)=1 means that there exists a path from node u
  8. % to node v; alternatively (u,v)=0.
  9. %
  10. % The distance matrix contains lengths of shortest paths between all
  11. % pairs of nodes. An entry (u,v) represents the length of shortest path
  12. % from node u to node v. The average shortest path length is the
  13. % characteristic path length of the network.
  14. %
  15. % Input: CIJ, binary (directed/undirected) connection matrix
  16. %
  17. % Outputs: R, reachability matrix
  18. % D, distance matrix
  19. %
  20. % Note: faster but more memory intensive than "breadthdist.m".
  21. %
  22. % Algorithm: algebraic path count.
  23. %
  24. %
  25. % Olaf Sporns, Indiana University, 2002/2007/2008
  26. % initialize
  27. R = CIJ;
  28. D = CIJ;
  29. powr = 2;
  30. N = size(CIJ,1);
  31. CIJpwr = CIJ;
  32. % Check for vertices that have no incoming or outgoing connections.
  33. % These are "ignored" by 'reachdist'.
  34. id = sum(CIJ,1); % indegree = column sum of CIJ
  35. od = sum(CIJ,2)'; % outdegree = row sum of CIJ
  36. id_0 = find(id==0); % nothing goes in, so column(R) will be 0
  37. od_0 = find(od==0); % nothing comes out, so row(R) will be 0
  38. % Use these columns and rows to check for reachability:
  39. col = setxor(1:N,id_0);
  40. row = setxor(1:N,od_0);
  41. [R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row);
  42. % "invert" CIJdist to get distances
  43. D = powr - D+1;
  44. % Put 'Inf' if no path found
  45. D(D==(N+2)) = Inf;
  46. D(:,id_0) = Inf;
  47. D(od_0,:) = Inf;
  48. %----------------------------------------------------------------------------
  49. function [R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row)
  50. % Olaf Sporns, Indiana University, 2002/2008
  51. CIJpwr = CIJpwr*CIJ;
  52. R = double(R | ((CIJpwr)~=0));
  53. D = D+R;
  54. if ((powr<=N)&&(~isempty(nonzeros(R(row,col)==0))))
  55. powr = powr+1;
  56. [R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row);
  57. end;