Magic matrices have sum of all rows and sum of all columns equal to some number. In addition, the sum of the primary and secondary cross diagonal equal that number, called the magic number. The magic number is only dependent on size of matrix.
The program will solve magic matrices for odd size, such as 11 by 11 (N = 11).
For a magic matrix, such as that of size 11 by 11, we have elements from 1 to 11 square. The magic number is the mean of all elements from 1 to N square, multiplied by N.
We use the matrix function to create a matrix and then loop, over the 2-dimensions, to get the individual elements, {1,2,3,...N^2}, into their correct positions. Magic matrices are not unique, there are many others, dependent on the algorithm, with the same sum property, however the magic number for a particular N is unique.
Lastly, we check all the relevant sums.
# ex26.R
N <- 11
magic_num <- sum(1:N^2)/N
mat <- function(i,j){
i <- (i-1) %% N
j <- (j-1) %% N
c(x = i+1, y = j+1)
}
A <- matrix(numeric(N^2), nrow = N)
st <- c(N-(N-1)/2,(N+3)/2)
for (k2 in 1:N) {
st <- c(st[1]+1,st[2]-1)
for (k in 1:N) {
cxy <- mat(st[1]+k-1,st[2]+k-1)
A[cxy["x"],cxy["y"]] <- k+(k2-1)*N
}
}
AR <- matrix(numeric(N^2),nrow = N)
for (k2 in 1:N) {
AR[k2,] <- rev(A[k2,])
}
cat('\nmagic(', N, ') = \n', sep = '')
print(A)
cat('\nmagic number =', magic_num)
cat('\nsum primary diag =', sum(diag(A)))
cat('\nsum secondary diag =', sum(diag(AR)))
for (k2 in 1:N) {
cat('\nsum row', k2, '=', sum(A[k2,]))
cat('\nsum col', k2, '=', sum(A[,k2]))
}
# magic(11) =
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
# [1,] 56 117 46 107 36 97 26 87 16 77 6
# [2,] 7 57 118 47 108 37 98 27 88 17 67
# [3,] 68 8 58 119 48 109 38 99 28 78 18
# [4,] 19 69 9 59 120 49 110 39 89 29 79
# [5,] 80 20 70 10 60 121 50 100 40 90 30
# [6,] 31 81 21 71 11 61 111 51 101 41 91
# [7,] 92 32 82 22 72 1 62 112 52 102 42
# [8,] 43 93 33 83 12 73 2 63 113 53 103
# [9,] 104 44 94 23 84 13 74 3 64 114 54
# [10,] 55 105 34 95 24 85 14 75 4 65 115
# [11,] 116 45 106 35 96 25 86 15 76 5 66
#
# magic number = 671
# sum primary diag = 671
# sum secondary diag = 671
# sum row 1 = 671
# sum col 1 = 671
# sum row 2 = 671
# sum col 2 = 671
# sum row 3 = 671
# sum col 3 = 671
# sum row 4 = 671
# sum col 4 = 671
# sum row 5 = 671
# sum col 5 = 671
# sum row 6 = 671
# sum col 6 = 671
# sum row 7 = 671
# sum col 7 = 671
# sum row 8 = 671
# sum col 8 = 671
# sum row 9 = 671
# sum col 9 = 671
# sum row 10 = 671
# sum col 10 = 671
# sum row 11 = 671
# sum col 11 = 671