flip — Reverse element order along dimensions in MATLAB and RunMat.
flip(A) reverses the order of elements in A along the first nonsingleton dimension, while flip(A, dim) reverses one positive integer-valued scalar dimension. Numeric dimension vectors, typed-integer or logical dimensions, and direction keywords are separately gated RunMat-only extensions.
Syntax
B = flip(A)
B = flip(A, dim_or_direction)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input array/value to reverse. |
dim_or_direction | Any | Yes | — | Dimension index/vector or direction keyword ('horizontal', 'vertical', 'both'). |
Returns
| Name | Type | Description |
|---|---|---|
B | Any | Input array with selected dimensions reversed. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:flip:TooManyInputs | More than one optional argument is provided after A. | flip: too many input arguments |
RunMat:flip:InvalidInput | Input type, dimension argument, or direction token is invalid. | flip: invalid input argument |
RunMat:flip:UnsupportedInput | Input type is unsupported for flip. | flip: unsupported input type |
How flip works
- Implemented inputs are numeric arrays, logical masks, complex arrays, and string or character arrays. Cell, struct, table, timetable, categorical, datetime, duration, and calendar-duration parity remains pending.
flip(A)locates the first non-singleton dimension and reverses that axis.flip(A, dim)flips along the dimensiondim(1-based, MATLAB-compatible).- RunMat extension:
flip(A, dims)accepts a nonempty row or column vector of unique positive dimensions. - RunMat extension: typed-integer and logical dimensions are exact structural controls; strict compatibility mode rejects them before parsing.
- RunMat extension:
flip(A, 'horizontal')andflip(A, 'vertical')map to dimensions 2 and 1, while'both'flips the first two dimensions. - All eight integer data classes preserve their exact storage and output class.
- Dimensions larger than
ndims(A)are allowed. RunMat pads trailing singleton axes so the request becomes a no-op, matching MATLAB semantics. - Reversing an empty dimension (extent zero) is a no-op.
- gpuArray inputs stay on the device: the runtime calls provider flip hooks when available and otherwise gathers, flips, and re-uploads the data.
Does RunMat run flip on the GPU?
When RunMat Accelerate is active, the runtime first checks whether the selected provider implements the flip hook (ProviderHook::Custom("flip")). Providers may specialise the operation using device-side kernels. If the hook is missing (common for the simple provider or builds without GPU support), RunMat gathers the tensor once, performs the flip on the host, and uploads the result back to the device. The returned value is still a gpuArray, ensuring residency is preserved for downstream fused expressions.
GPU memory and residency
No additional steps are required. RunMat keeps tensors on the GPU across fused expressions. You can opt-in explicitly with gpuArray for MATLAB compatibility, but the auto-offload planner already tracks residency and minimises host/device copies even when a provider falls back to the gather → flip → upload pathway.
Examples
Reversing a Row Vector
row = 1:5;
rev = flip(row)Expected output:
rev = [5 4 3 2 1]Reversing Matrix Rows (Vertical Flip)
A = [1 2 3; 4 5 6; 7 8 9];
B = flip(A)Expected output:
B =
7 8 9
4 5 6
1 2 3Flipping Columns with the Horizontal Direction Keyword
A = magic(3);
H = flip(A, 'horizontal')Expected output:
H =
2 7 6
9 5 1
4 3 8Flipping Along Multiple Dimensions
T = reshape(1:8, [2 2 2]);
F = flip(T, [1 3])Expected output:
F(:,:,1) =
3 4
1 2
F(:,:,2) =
7 8
5 6Flipping Character Data
C = ['r','u','n'; 'm','a','t'];
Ct = flip(C, 'horizontal')Expected output:
Ct =
'nur'
'tam'Flipping gpuArray Data While Staying on the Device
G = gpuArray(rand(4, 4));
V = flip(G, 'vertical');
isgpuarray(V)Expected output:
ans = logical 1Using flip with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how flip changes the result.
Run a small flip example, explain the result, then change one input and compare the output.
FAQ
Which dimension does flip(A) use by default?⌄
The first dimension whose size is greater than one. Column vectors flip along dimension 1, row vectors flip along dimension 2.
What happens if I pass a dimension larger than ndims(A)?⌄
Nothing changes; RunMat pads missing axes with singleton dimensions, so the flip becomes a no-op, just like MATLAB.
Do direction keywords work with any array type?⌄
Yes. 'horizontal' maps to dimension 2, 'vertical' to dimension 1, and 'both' applies both flips in sequence.
Can I flip logical or string arrays?⌄
Absolutely. Logical results stay logical, and string arrays preserve string elements while reordering their positions.
Does flipping modify gpuArray data in place?⌄
No. The builtin returns a new gpuArray handle. Providers may recycle buffers, but the original value remains unchanged.
What about complex inputs?⌄
Complex scalars and arrays are reversed just like real data. Scalars remain complex scalars after the operation.
Related Array functions
Shape
blkdiag · cat · circshift · diag · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · toeplitz · tril · triu · vertcat
Grouping
accumarray · combinations · discretize · findgroups · groupcounts · grp2idx · splitapply
Sorting Sets
argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how flip is executed, line by line, in Rust.
- View the source for flip in Rust on GitHub
- Learn how the RunMat 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 blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.