%the program computes classes for a transition matrix
%the input is a binary matrix, whereby 1s represent 
%the nonzero transitions 

%input
n=4; 

P=[1 1 0 0; 
   1 1 0 0; 
   0 0 1 1; 
   0 0 0 1];

%random matrix 

% n=10;
% p=0.15;
% P=(rand(n,n)<p);

fprintf('P= ');
for (i=1:n)
    fprintf('%2d', i);
end
fprintf('\n    ');
for (i=1:n)
    fprintf('--');
end
fprintf('\n');

P1=((eye(n)+P)>0);

for (i=1:n)
    fprintf('%2d|', i); 
    for (j=1:n)
        fprintf(' %d', P1(i,j)); 
    end
    fprintf('\n');
end
    
fprintf('CLASSES:\n');

Q=(P1^2>0); 

while ~(isequal(P1,Q))
  P1=Q;
  Q=(P1^2>0); 
end
sf=zeros(1,n); 
ncl=0; maxcls=0;
for (i=1:n)
   if (sf(i)==0)
      ncl=ncl+1; 
      cls=0;
      %fprintf('%d:',i); 
      sf(i)=1; 
      closed=1; 
      for (j=1:n)
          if ((Q(i,j)>0)&&(Q(j,i)>0))
             fprintf('%d ',j); 
             sf(j)=1;
             cls=cls+1;
          elseif (Q(i,j)>0)
             closed=0; 
          end
      end
 
     % fprintf(' size=%d ', cls); 
      if (cls>maxcls) maxcls=cls;
      end
      if (closed) 
          fprintf(' r\n');
      else
          fprintf(' t\n');
      end
      
          
      %fprintf('\n'); 
   end
end
fprintf('no of classes=%d\n', ncl);
fprintf('max size of class=%d\n', maxcls);
 

 








   
