5827
|
1 ## Copyright (C) 1999-2001 Paul Kienzle |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} magic (@var{n}) |
|
22 ## |
|
23 ## Create an @var{n}-by-@var{n} magic square. Note that @code{magic |
|
24 ## (@var{2})} is undefined since there is no 2-by-2 magic square. |
|
25 ## |
|
26 ## @end deftypefn |
|
27 |
|
28 function A = magic(n) |
|
29 |
|
30 if (nargin != 1) |
|
31 print_usage (); |
|
32 endif |
|
33 |
|
34 if (n != floor (n) || n < 0 || n == 2) |
|
35 error ("magic: n must be an positive integer not equal to 2"); |
|
36 endif |
|
37 |
|
38 if (n == 0) |
|
39 |
|
40 A = []; |
|
41 |
|
42 elseif (mod (n, 2) == 1) |
|
43 |
|
44 shift = floor ((0:n*n-1)/n); |
|
45 c = mod ([1:n*n] - shift + (n-3)/2, n); |
|
46 r = mod ([n*n:-1:1] + 2*shift, n); |
|
47 A (c*n+r+1) = 1:n*n; |
|
48 A = reshape (A, n, n); |
|
49 |
|
50 elseif (mod (n, 4) == 0) |
|
51 |
|
52 A = reshape (1:n*n, n, n)'; |
|
53 I = [1:4:n, 4:4:n]; |
|
54 J = fliplr (I); |
|
55 A(I,I) = A(J,J); |
|
56 I = [2:4:n, 3:4:n]; |
|
57 J = fliplr (I); |
|
58 A(I,I) = A(J,J); |
|
59 |
|
60 elseif (mod (n, 4) == 2) |
|
61 |
|
62 m = n/2; |
|
63 A = magic (m); |
|
64 A = [A, A+2*m*m; A+3*m*m, A+m*m]; |
|
65 k = (m-1)/2; |
|
66 if (k>1) |
|
67 I = 1:m; |
|
68 J = [2:k, n-k+2:n]; |
|
69 A([I,I+m],J) = A([I+m,I],J); |
|
70 endif |
|
71 I = [1:k, k+2:m]; |
|
72 A([I,I+m],1) = A([I+m,I],1); |
|
73 I = k + 1; |
|
74 A([I,I+m],I) = A([I+m,I],I); |
|
75 |
|
76 endif |
|
77 |
|
78 endfunction |
|
79 |
|
80 %!test |
|
81 %! for i=3:30 |
|
82 %! A=magic(i); |
|
83 %! assert(norm(diff([sum(diag(A)),sum(diag(flipud(A))),sum(A),sum(A')])),0) |
|
84 %! endfor |
|
85 %!assert(isempty(magic(0))); |
|
86 %!assert(magic(1),1); |
|
87 %!error magic(2) |