function Aufgabe5
%Aufgabe5 - plot some statistics of USPS dataset: class means, std deviations and outliers. 
%
%usage
%  Aufgabe5
%
%description
%  Aufgabe5 loads the USPS dataset (from usps.mat) and plots 
%   1. the class means;
%   2. the standard deviation of classes 1, 2 and 7; and
%   3. the three datapoints of classes 1, 2, and 7 which are most distant from 
%      the respective class means.
%
%author
%  buenau@cs.tu-berlin.de

load usps.mat;

n = size(data_patterns, 2);

% Plot class means. 
colormap gray;
for i=1:10
  subplot(2, 5, i);
  imagesc(reshape(mean(data_patterns(:,find(data_labels(i,:) == 1)), 2), [16 16])');  
  axis off;
  title(sprintf('Mean of class %d', i-1));
end

figure;
ci = [ 2 3 8 ];

% Plot standard deviations of classes 1, 2, 7. 
for i=1:length(ci)
  subplot(3,1,i);
  bar3(reshape(std(data_patterns(:,find(data_labels(ci(i),:) == 1)), [], 2), [16 16])');  axis off;
  title(sprintf('Stddev of class %d', ci(i)-1));
end

% Find and plot outliers of classes 1, 2, 7.

% Compute squared distance matrix.
xx = sum( data_patterns .^ 2, 1);
D = repmat(xx, [n 1]) -2*data_patterns'*data_patterns + repmat(xx', [1 n]);

figure;
colormap gray;

for i=1:length(ci)
  c_ii = find(data_labels(ci(i),:) == 1);
  m = mean(data_patterns(:,c_ii), 2);
  dist = sum( ( data_patterns(:,c_ii) - repmat(m, [1 length(c_ii)]) ) .^ 2, 1 );
  [foo, s_ii ] = sort(-dist);

  for j=1:3
    subplot(3, 3, sub2ind([3 3], i, j));
    imagesc(reshape(data_patterns(:,c_ii(s_ii(j))), [16 16])');
    if j == 1, title(sprintf('Outliers of class %d', ci(i)-1)); end
  end
end
