function som_9_12(epochs)

% function som_9_12(epochs)
% 
% This program recreates Figure 9.12 from textbook.
% Use SOM to learn. In this example inputs are 2-D points with features
% uniformly distributed in [-1, 1] range. Plots data and learned SOM.
% 
% Inputs : epochs      - number of training epochs.
% Outputs: none.
%
% Author : Nemanja Djuric
% Date   : Sept. 25th, 2010
%
% Warning: Check line 29 of this file for compatibility issues.

% check input
if (epochs < 1)
    disp('Error: Invalid input, epochs must be a positive integer.');
    return;
end;

% definitions
def_som_size = 8;

% create 1000 2-D point, features are in [-1, 1] range
data = rands(2, 1000);

% old version of newsom() is used here (tested on Matlab 7.0.0.19920), new 
%   version of newsom() is commented below (Matlab 7.7.0.471)

% get range of features, needed for initialization of SOM
min_max = minmax(data);
% create new SOM (old version), which will have 8x8 grid structure
% structure can be: gridtop, hextop, randtop
net = newsom(min_max, [def_som_size def_som_size], 'gridtop');

% create new SOM (new version), which will have 8x8 grid structure
% net = newsom(data, [def_som_size def_som_size], 'gridtop');

% plot new SOM topology
figure(1), clf;
plotsom(net.layers{1}.positions);
title('SOM topology');
pause;
close;

% train the SOM
net.trainParam.epochs = epochs;
net.trainParam.show = 10;
net = train(net, data);

% plot the data overlayed by SOM, observe that SOM learned the topology
% of inputs' space
plot(data(1, :), data(2, :), 'g.', 'markersize', 20);
hold on;
plotsom(net.iw{1,1}, net.layers{1}.distances, 1);
hold off;
pause;
close;