Skip to content

Instantly share code, notes, and snippets.

@hidde-jan
Last active December 24, 2015 11:38
Show Gist options
  • Save hidde-jan/6791851 to your computer and use it in GitHub Desktop.
Save hidde-jan/6791851 to your computer and use it in GitHub Desktop.
Some quick 'n dirty matlab functions for working with graphs and their important matrices.
function easygplot( A )
%EASYGPLOT What gplot should do by default.
% EASYGPLOT puts all nodes on a circle equidistantly starting at (1, 0)
% and going counter clockwise. 2-way edges are plotted in black, edges
% from node i to node j with i < j are plotted in blue, and edges from
% node j to i with j > i are plotted in red.
%
% It's assumed that A(i,j) = 1 if there is an edge from j into i, and
% A(i,j) is zero otherwise.
% Parts where stolen from http://www.mathworks.nl/matlabcentral/fileexchange/16131-plot-a-directed-graph
n = size(A, 1);
t = linspace(0, 2*pi, n + 1);
coords = [cos(t(1:n))' sin(t(1:n))'];
dA = A .* (1 - A'); % Directed edges (1-way)
dAl = tril(dA, -1); % Directed edges (1-way, i -> j with i < j)
dAu = triu(dA, 1); % directed edges (1-way, j -> i with j > i)
uA = A - dA; % Undirected edges (2-way, i -> j and j -> i)
figure(); % Open a new figure every time.
gplot(uA, coords, '-k');
hold on;
gplot(dAl, coords, '-b');
gplot(dAu, coords, '-r');
hold off;
end
function mat2tex( matrix, varargin )
%MAT2TEX Print a matrix in TeX format.
% MAT2TEX allows you to print a matrix to (La)TeX. It outputs the
% matrix as a \begin{env}...\end{env} block, where env defaults to
% pmatrix. Each element of the matrix is printed in a supplied fmt
% which is '%d' by default.
if nargin > 2
env = varargin{1};
fmt = varargin{2};
elseif nargin == 2
env = varargin{1};
fmt = '%d';
else
env = 'pmatrix';
fmt = '%d';
end
fprintf('\n\\begin{%s}\n', env);
[n,m] = size(matrix);
for i = 1:n
fprintf(' ');
for j = 1:m
fprintf(fmt, matrix(i,j));
if j < m
fprintf(' %s ', '&');
end
end
if i < n
fprintf(' %s', '\\');
end
fprintf('\n');
end
fprintf('\\end{%s}\n\n', env);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment