%% loaddata
% This script downloads the non-tabular text data in unfamiliar format and
% extract the portion we want.
%
% The file first lists 34 vertices (nodes) along with their id's. Then it
% lists edges between two vertices identified by their id's. Those two
% sections have headers like '*Vertices 34' and '*Edges'. We can look for
% '*Edges' and read the rest of the text to get the edge list. Then we can
% read the node names from the first section. 
% 
%  *Vertices 34
%  1 "1"
%  2 "2"
%  3 "3"
%  4 "4"
%  :
%  :
%  34 "34"
%  *Edges
%  1 2
%  1 3
%  2 3
%  1 4
%  :
%  :

% here is the URL of the file
url = 'http://networkdata.ics.uci.edu/data/karate/karate.paj';
% download the data
data = webread(url);
% preview the dataset
disp(data(1:47))
% the text data has two sections - detect the header that separates them
sep = strfind(data, '*Edges');
% read the edges section and convert the string to double
edges = textscan(data(sep+8:end), '%f %f', 'Delimiter', '\n'); 
edges = cell2mat(edges);
% read the vertices (= nodes) section and extract node names
nodes = textscan(data(15:sep-1), '%f %q', 'Delimiter', '\n');
name = nodes{2};
% remove unnecessary variables
clearvars -except edges name
% save what we need
if exist('karate.mat', 'file') == 0
    save('karate.mat')
end