magic — Generate an n-by-n magic square.
magic(n) returns an n x n matrix filled with the integers 1:n^2 such that every row, column, and main diagonal has the same sum. RunMat follows MATLAB's construction rules for odd, doubly-even, and singly-even orders.
How does the magic function behave in MATLAB / RunMat?
magic(n)requires a single non-negative integer scalarn.magic(1)returns1, whilemagic(0)returns an empty0 x 0matrix.magic(2)is undefined and raises an error (no 2x2 magic square exists).- Odd, doubly-even (
n % 4 == 0), and singly-even (n % 4 == 2) orders each use MATLAB's standard construction so results match MATLAB outputs.
GPU behavior
RunMat gathers any GPU-resident inputs before evaluating magic and returns a host tensor. No acceleration provider hooks are defined for this builtin yet.
GPU residency
magic always runs on the host CPU today. If you need the result on the GPU, wrap the call in gpuArray(...).
Examples of using magic in MATLAB / RunMat
A 3x3 magic square
M = magic(3)Expected output:
M =
8 1 6
3 5 7
4 9 2A 4x4 magic square
M = magic(4)Expected output:
M =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1Use magic squares as structured input
A = magic(5);
result = A * A'FAQ
Why does magic(2) fail?
No 2x2 magic square exists, so MATLAB (and RunMat) report an error for order 2.
Does magic accept a size vector?
No. magic accepts a single scalar order. Use ones, zeros, or eye when you need a size vector form.
How do I move the result to the GPU?
Call gpuArray(magic(n)) if you need the output on the GPU. RunMat computes magic on the host today.
See also
Source & Feedback
- Source code: `crates/runmat-runtime/src/builtins/array/creation/magic.rs`
- Found a bug? Open an issue with a minimal reproduction.