Language Reference


MAGIC Function

MAGIC (n);

The MAGIC function is part of the IMLMLIB library . The MAGIC function returns an n$\times $n magic square for n$ >2$. The matrix M is a magic square if it contains the integers 1, 2, …, n$^2$. If s is the trace of M, then M satisfies the following conditions:

  • The sum of every row is s.

  • The sum of every column is s.

  • The sum of the antidiagonal is s.

There are many algorithms for creating magic squares. The algorithm implemented in the MAGIC function is based on Moler (2011).

The MAGIC function is mainly used to generate examples for documentation, discussion forums, books, and so forth. The following example displays two magic squares:

m3 = Magic(3);
m4 = Magic(4);
print m3, m4;

Figure 24.204: Magic Squares of Size 3 and 4

m3
8 1 6
3 5 7
4 9 2

m4
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1