Mercurial > octave
comparison scripts/special-matrix/magic.m @ 25235:27e6b38571d3
magic.m: Issue an error if input N is negative (bug #53441).
* magic.m: Check for negative N and call error() if found.
Add BIST test to check new code.
author | Dildar Sk <dildarsk101010@gmail.com> |
---|---|
date | Fri, 23 Mar 2018 19:03:45 -0400 |
parents | 6652d3823428 |
children | 00f796120a6d |
comparison
equal
deleted
inserted
replaced
25234:b02d5a4c7452 | 25235:27e6b38571d3 |
---|---|
34 if (nargin != 1) | 34 if (nargin != 1) |
35 print_usage (); | 35 print_usage (); |
36 endif | 36 endif |
37 | 37 |
38 n = fix (n); | 38 n = fix (n); |
39 if (n < 1) | 39 if (n < 0) |
40 | 40 error ("magic: N must be non-negative"); |
41 elseif (n < 1) | |
41 A = []; | 42 A = []; |
42 | |
43 elseif (mod (n, 2) == 1) | 43 elseif (mod (n, 2) == 1) |
44 | 44 |
45 shift = floor ((0:n*n-1)/n); | 45 shift = floor ((0:n*n-1)/n); |
46 c = mod ([1:n*n] - shift + (n-3)/2, n); | 46 c = mod ([1:n*n] - shift + (n-3)/2, n); |
47 r = mod ([n*n:-1:1] + 2*shift, n); | 47 r = mod ([n*n:-1:1] + 2*shift, n); |
89 ## While one day we may change the actual return of magic (2), | 89 ## While one day we may change the actual return of magic (2), |
90 ## this properties still must be true. | 90 ## this properties still must be true. |
91 %!test <*46672> | 91 %!test <*46672> |
92 %! m = magic (2); | 92 %! m = magic (2); |
93 %! assert (size (m), [2 2]); | 93 %! assert (size (m), [2 2]); |
94 %! assert (unique (m), [1; 2; 3; 4]); | 94 %! assert (m, [4 3; 1 2]); |
95 | 95 |
96 %!assert (magic (2), [4 3; 1 2]) | |
97 %!assert (isempty (magic (-1))) | |
98 %!assert (isempty (magic (0))) | 96 %!assert (isempty (magic (0))) |
99 %!assert (magic (1), 1) | 97 %!assert (magic (1), 1) |
100 %!assert (magic (1.5), 1) | 98 %!assert (magic (1.5), 1) |
101 | 99 |
102 ## Test input validation | 100 ## Test input validation |
103 %!error magic () | 101 %!error magic () |
104 %!error magic (1, 2) | 102 %!error magic (1, 2) |
103 %!error <N must be non-negative> magic (-5) |