
Matrices and Mag ic Squares
and
sum(diag(A))
produces
ans =
34
The other diagonal, the so-called antidiagonal, is not so important
mathematically, so MATLAB does not have a ready-made function for it.
But a function originally intended for use in graphics,
fliplr,flipsamatrix
from left to right:
sum(diag(fliplr(A)))
ans =
34
You h ave verified that the matrix in Dürer’s en graving is indeed a magic
square and, in the process, have sampled a few MATLAB matrix operations.
The following sections continue to use this m atrix to illustrate additional
MATLAB capabilities.
Subscripts
The element in row i and column j of A is d e n o ted by A(i,j). For example,
A(4,2) is the number in the fourth row and second column. For our m agic
square,
A(4,2) is 15. So to compute the sum of the elements in the fourth
column of
A,type
A(1,4) + A(2,4) + A(3 ,4) + A(4,4)
This produces
ans =
34
but is not the most elegant way of summing a single column.
It is also possible to refer to the elements of a matrix with a single subscript,
A(k). This is the usual way of referencing row and column vectors. But it
can a lso apply to a fully two-dimensional m atrix, in which case the array is
2-7
Komentarze do niniejszej Instrukcji