1

I was trying to create random magic square in Octave and tried something like rand(magic(3)), and it gave unexpected endless results something like this:

 ans(:,:,1,1,2,1,1,1,1) =

 0.894903   0.296415   0.143990
 0.186976   0.305691   0.505485
 0.224823   0.834031   0.285508
 0.336706   0.318158   0.076293 

On trying rand(magic(4)) and for 5,6,7... it gave a message something like this

error: out of memory or dimension too large for Octave's index type

What can be the possible reason for this vague result ?

Dan
  • 45,079
  • 17
  • 88
  • 157
  • 1
    what are you trying to do? magic(3) returns a 3x3 matrix. The function rand expects as arguments number of elements per dimension so you're creating a 8x3x4x1x5x9x6x7x2 matrix. For rand(magic(4)) the matrix would have prod(magic(4)(:))=20922789888000 elements which is too big to fit into memory – Andy Sep 28 '15 at 10:09
  • I saw the comments to Dan's answer, they are partially clarifying the problem. While `magic(n)` returns a square with the numbers `1:n*n` you are just talking about not-repeating numbers. That opens much more capabilities. Please update your question and make clear what a magic square is. – Daniel Sep 28 '15 at 11:27

1 Answers1

2

What are you trying to do? magic(3) creates a 3-by-3 matrix in which all the rows and columns add up to the same number. rand(x) creates an n-dimensional matrix of uniformly distributed random numbers. If you call y = rand([1,2,3]) for example, you will get a 3-dimensional matrix of uniformly distributed numbers. The dimensions of y will match your input i.e. size(y) should return [1,2,3] and the number of elements will be prod(y). Thus the number of elements of rand(magic(3)) should be equal to prod(prod(magic(3))) which is 362880. If you do this for rand(magic(4)) then the number of elements would be over 20 trillion which is why you are running out of memory.

Dan
  • 45,079
  • 17
  • 88
  • 157
  • Then how can I create a random magic square? I mean octave returns the same n*n magic square everytime. – Himagra Chawla Sep 28 '15 at 10:47
  • A matrix in which sum of all the elements of rows and columns is same. – Himagra Chawla Sep 28 '15 at 10:50
  • And the diagonals? With the diagonals, I don't think you can create a random magic square (unless you randomly pick from the 8 equivalent matrices you'd get from rotation and reflection...). If you ignore diagonals then just shuffle the rows and columns around... – Dan Sep 28 '15 at 10:52
  • Yes the sum of elements of diagonals should be same and no number should repeat. – Himagra Chawla Sep 28 '15 at 10:54
  • @HimagraChawla: Any reason you don't accept this as answer? – Andy Sep 30 '15 at 13:39