Getting Started |
sum, transpose, and diag
You are probably already aware that the special properties of a magic square have to do with the various ways of summing its elements. If you take the sum along any row or column, or along either of the two main diagonals, you will always get the same number. Let us verify that using MATLAB. The first statement to try is
When you do not specify an output variable, MATLAB uses the variable ans
, short for answer, to store the results of a calculation. You have computed a row vector containing the sums of the columns of A
. Sure enough, each of the columns has the same sum, the magic sum, 34.
How about the row sums? MATLAB has a preference for working with the columns of a matrix, so the easiest way to get the row sums is to transpose the matrix, compute the column sums of the transpose, and then transpose the result. The transpose operation is denoted by an apostrophe or single quote, '
. It flips a matrix about its main diagonal and it turns a row vector into a column vector.
produces a column vector containing the row sums
The sum of the elements on the main diagonal is obtained with the sum
and the diag
functions:
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
, flips a matrix from left to right:
You have verified that the matrix in Dürer's engraving is indeed a magic square and, in the process, have sampled a few MATLAB matrix operations. The following sections continue to use this matrix to illustrate additional MATLAB capabilities.
Entering Matrices | Subscripts |
© 1994-2005 The MathWorks, Inc.