Language Reference

MAGIC Function

MAGIC (n) ;

This function is supported by the IML procedure and the iml action.

The MAGIC function is part of the IMLMLIB library. The MAGIC function returns an ntimesn magic square for ngreater-than 2. The matrix M is a magic square if it contains the integers 1, 2, …, nsquared. 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 241: Magic Squares of Size 3 and 4

m3
816
357
492

m4
162313
511108
97612
414151


Last updated: July 20, 2026