0

I am wondering how to create a matrix with random natural numbers but with the sum of every column equal to sum of every row and diagonal sum also.

I mean that you create a function that by choosing dimension and sum of the rows, columns and diagonals gives you a square matrix as described above but with different numbers on each row and column.

Does anybody know how to make this happen?

I want to create a function on my own without any packages to fully understand the program.

M--
  • 25,431
  • 8
  • 61
  • 93
Artur Si
  • 31
  • 1
  • 2
    If the sum of each column is the sum of each row then a lot of numbers depend on others and can't be random – HubertL May 30 '17 at 19:45
  • 1
    Are you talking about a [magic square](https://en.wikipedia.org/wiki/Magic_square)? Check out the wikipedia article for tips on construction. – MrFlick May 30 '17 at 19:46
  • 3
    `magic::magic(4)` – M-- May 30 '17 at 19:52

1 Answers1

5

You can use a package called magic:

library(magic)
magic(4)

output looks like this:

#      [,1] [,2] [,3] [,4] 
# [1,]    1   12    8   13 
# [2,]   15    6   10    3 
# [3,]   14    7   11    2 
# [4,]    4    9    5   16

You cannot decide what is the sum for the matrix. It is going to be:

enter image description here.

Where "n" is the dimension of the matrix.

But you can multiply it by a number (preferably an integer).

Useful Link: What is Magic Square?

How to look into a function?

If you want to figure out how magic function works, you can use this and dig into it step-by-step;

>functionBody(magic)

# { 
#     if (length(n) > 1) { 
#         return(sapply(n, match.fun(sys.call()[[1]]))) 
#     } 
#     n <- round(n) 
#     if (n == 2) { 
#         stop("Normal magic squares of order 2 do not exist") 
#     } 
#     if (n%%2 == 1) { 
#         return(as.standard(magic.2np1(floor(n/2)))) 
#     } 
#     if (n%%4 == 0) { 
#         return(as.standard(magic.4n(round(n/4)))) 
#     } 
#     if (n%%4 == 2) { 
#         return(as.standard(magic.4np2(round((n - 2)/4)))) 
#     } 
#     stop("This cannot happen") 
# }

You need to look into other functions that appears above to fully comprehend the process.

Community
  • 1
  • 1
M--
  • 25,431
  • 8
  • 61
  • 93