%function digraph2(file)
%DIGRAPH  Generate and analyze text digraph frequency matrix.
%  DIGRAPH(filename)
%  Example
%     digraph('gettysburg.dat')

clear all; bigscreen;
file = 'gettysburg.dat';

% Read entire file

format short g;
fid = fopen(file);
txt = fread(fid);
fclose(fid);
alphabet = char(('A':'Z')'); 
blanks = char(32*ones(26,9));

% Convert to integers between 1 and 26

k = upper(char(txt)) - 'A' + 1;
k(k < 1 | k > 26) = [];

% Generate the digraph frequency matrix and compute its SVD

j = k([2:length(k) 1]);
A = full(sparse(k,j,1,26,26)),
% frequency vector
cnt = sum(A,2);
[U,S,V] = svd(A);

disp(' ');
% display the singular values
disp('            n    singular values');
disp('================================');
disp( [(1:26)' diag(S)]);

% display the first left and right singular vectors, and the frequency
% vector
disp(' ');
disp('               U(:,1)              V(:,1)           f')
disp('=======================================================');
disp([alphabet blanks num2str(U(:,1)) blanks num2str(V(:,1)) blanks num2str(cnt)])

% display the first left and right singular vectors, and the frequency
% vector after appropriate scaling
disp(' ');
disp('          U(:,1)/sum(U(:,1))   V(:,1)/sum(V(:,1))     f/sum(f)')
disp('=================================================================');
disp([alphabet blanks num2str(U(:,1)/sum(U(:,1))) blanks num2str(V(:,1)/sum(V(:,1))) blanks num2str(cnt/sum(cnt))])


% Plot the second left and right singular vectors

shg
clf
s = 4/3*max(max(abs(U(:,2))),max(abs(V(:,2))));
axis(s*[-1 1 -1 1])
axis square
for i = 1:26
   if cnt(i) > 0
      text(U(i,2),V(i,2),char('A'+i-1))
   end
end
line([0 0],[-s s],'color','b')
line([-s s],[0 0],'color','b')
box
title(sprintf('%d characters',length(k)))

% display the second left and right singular vectors
disp(' ');
disp('               U(:,2)              V(:,2)')
disp('=============================================');
disp([alphabet blanks num2str(U(:,2)) blanks num2str(V(:,2))])
