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 magic works in 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.
How magic runs on the GPU
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 memory and residency
magic always runs on the host CPU today. If you need the result on the GPU, wrap the call in gpuArray(...).
Examples
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.
Related functions to explore
These functions work well alongside magic. Each page has runnable examples you can try in the browser.
ones, eye, conv2, colon, false, fill, linspace, logspace, meshgrid, rand, randi, randn, randperm, range, true, zeros
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how magic works, line by line, in Rust.
- View magic.rs on GitHub
- Learn how the runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code — faster, on any GPU, with no license required.
- Simulations that took hours now take minutes. RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed.
- Start running code in seconds. Open the browser sandbox or download a single binary. No license server, no IT ticket, no setup.
- A full development environment. GPU-accelerated 2D and 3D plotting, automatic versioning on every save, and a browser IDE you can share with a link.