30
Matrix Operations and Applications
You can create a diagonal matrix with the given elements by using the diag command as follows:
>> d = [1 3 5 7], A = diag(d)
d =
1 3 5 7
A =
1 0 0 0
0 3 0 0
0 0 5 0
0 0 0 7
Many times, special matrices are required for testing your functions. One command that is
frequently used in such cases is magic. The magic function creates a square matrix in which
the sum of elements in all columns and rows and the two diagonals are equal. Consider the fol-
lowing example:
>> z = magic(3) % gives the following matrix
z =
8 1 6
3 5 7
4 9 2
2.4.4 Concatenation
Larger matrices can be formed by concatenating smaller matrices. The pair of square brackets,
[ ], is also known as the concatenation operator. The basic idea behind ...