Search code examples
matlaboctavemagic-square

Random magic matrix giving unexpected results


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 ?


Solution

  • 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.