This is a brief introduction to using matlab, with an emphasis on handling graphs.
The basic objects in matlab are vectors and matrices.
We can create vectors like this:
>> v = [1, 2, 3]
v =
1 2 3
>> w = [3; 4; 5]
w =
3
4
5
To take the transpose of a vector, follow it by ':
>> w'
ans =
3 4 5
To turn anything into a column vector, follow it by (:):
>> w(:)
ans =
3
4
5
>> v(:)
ans =
1
2
3
We can operate naturally on vectors. Use semicolons to suppress output:
>> v + w'
ans =
4 6 8
>> c = v*w;
>> c
c =
26
>> w*v
ans =
3 6 9
4 8 12
5 10 15
We can create matrices similarly:
>> A = [1, 0, 0; 1, 1, 1; 0, 1, 1]
A =
1 0 0
1 1 1
0 1 1
>> A'
ans =
1 1 0
0 1 1
0 1 1
If I wanted to create a symmetric matrix out of A, I would add it to its transpose:
>> A + A'
ans =
2 1 0
1 2 2
0 2 2
But, if we want a graph then we just want the positions of the non-zero entries.
Here are two ways to get them. The first is to test which entries are greater than 0:
>> S = A + A' > 0;
>> S
S =
1 1 0
1 1 1
0 1 1
Matlab also distinguishes between numerical and logical matrices.
S is logical:
>> whos
Name Size Bytes Class Attributes
A 3x3 72 double
S 3x3 9 logical
As this sometimes causes difficulty, I usually force it to be numerical with a line like:
>> S = double(A + A' > 0);
>> whos
Name Size Bytes Class Attributes
A 3x3 72 double
S 3x3 72 double
S has a bunch of diagonal entries that we would probably like to get rid of.
To do this, I use the command diag. When applied to a matrix, it returns the
vector containing the diagonal. When applied to a vector, it returns the matrix
with those entries on the diagonal.
>> M = diag([1 2 3])
M =
1 0 0
0 2 0
0 0 3
>> diag(M)
ans =
1
2
3
To subtract the diagonal off of S, I write
>> S = S - diag(diag(S))
S =
0 1 0
1 0 1
0 1 0
Matlab also distinguishes between full and sparse matrices.
The difference is that full matrices store all the 0s, while sparse matrices
only store the location of the non-zero entries.
You can create a sparse matrix from a full matrix like this:
>> Ssparse = sparse(S)
Ssparse =
(2,1) 1
(1,2) 1
(3,2) 1
(2,3) 1
>> whos
Name Size Bytes Class Attributes
A 3x3 72 double
M 3x3 72 double
S 3x3 72 double
Ssparse 3x3 96 double sparse