union — Return unions of input arrays with MATLAB-compatible ordering and optional index outputs.
union(A, B) returns distinct values (or rows) appearing in either input and supports MATLAB-compatible ordering modes and optional index outputs that map back to A and B.
Syntax
C = union(A, B)
C = union(A, B, option...)
[C, ia] = union(A, B)
[C, ia] = union(A, B, option...)
[C, ia, ib] = union(A, B)
[C, ia, ib] = union(A, B, option...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | First input array. |
B | Any | Yes | — | Second input array. |
option | StringScalar | Variadic | — | Option tokens: 'rows'|'sorted'|'stable'. |
Returns
| Name | Type | Description |
|---|---|---|
C | Any | Union values or rows. |
ia | NumericArray | Indices selecting contributions from A. |
ib | NumericArray | Indices selecting contributions from B. |
Returned values from union depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:union:LegacyOptionUnsupported | Legacy compatibility options are requested. | union: the 'legacy' behaviour is not supported |
RunMat:union:ConflictingOrderOptions | Both 'sorted' and 'stable' options are provided. | union: cannot combine 'sorted' with 'stable' |
RunMat:union:UnknownOption | An unsupported option token is provided. | union: unrecognised option |
RunMat:union:RowsColumnMismatch | 'rows' mode is used and column counts differ. | union: inputs must have the same number of columns when using 'rows' |
RunMat:union:UnsupportedInputType | Input values cannot be converted into supported union domains. | union: unsupported input type |
RunMat:union:InvalidArgument | Option arguments are not string-like where required. | union: expected string option arguments |
RunMat:union:Internal | Internal conversion/allocation/provider decode fails. | union: internal operation failed |
How union works
union(A, B)flattens the inputs column-major, removes duplicates, and returns the sorted union of their values.[C, IA, IB] = union(A, B)also returns index vectors whereIApoints to the elements inAthat contribute toCandIBrefers to the elements inBthat only appear inB.union(A, B, 'stable')preserves the first-seen order: unique values fromAappear first, followed by new values appearing inB.union(A, B, 'rows')treats each row as a record. Inputs must share the same number of columns.- Character arrays and string arrays are fully supported in both element and row modes.
- Complex values follow MATLAB's ordering rules (magnitude first, then real/imaginary parts).
- Legacy compatibility flags (
'legacy'or'R2012a') are not supported in RunMat.
Does RunMat run union on the GPU?
union is registered as a residency sink. When tensors live on a GPU and the active provider does not expose a dedicated union hook, the runtime gathers them to host memory and executes the CPU implementation to guarantee MATLAB-compatible output.
Future providers may implement ProviderHook::Custom("union") to keep data on the device.
Examples
Combining Two Numeric Vectors
A = [5 7 1];
B = [3 1 1];
[C, IA, IB] = union(A, B)Expected output:
C =
1
3
5
7
IA =
3
1
2
IB =
1Preserving Input Order with 'stable'
A = [5 7 1];
B = [3 2 4];
C = union(A, B, 'stable')Expected output:
C =
5
7
1
3
2
4Union of Matrix Rows
A = [1 2; 3 4; 1 2];
B = [3 4; 5 6];
[C, IA, IB] = union(A, B, 'rows')Expected output:
C =
1 2
3 4
5 6
IA =
1
2
IB =
2Working with Character Arrays
A = ['m','z'; 'm','a'];
B = ['a','x'; 'm','a'];
union(A, B)Expected output:
ans =
4x1 char array
a
m
x
zUnion on GPU Data
G = gpuArray([1 4 2 5]);
H = gpuArray([2 6]);
[C, IA, IB] = union(G, H)Expected output:
C =
1
2
4
5
6
IA =
1
3
4
IB =
2Using union with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how union changes the result.
Run a small union example, explain the result, then change one input and compare the output.
FAQ
How are the index outputs defined?⌄
IA lists the positions in A that contribute to C. IB lists the positions in B for union values that do not already appear in A. Both use MATLAB's one-based indexing.
What happens if I request 'stable' ordering?⌄
The output keeps the first occurrence order: all unique values from A appear first, followed by new values from B in the order they are encountered.
Can I use 'rows' with string or character arrays?⌄
Yes. union accepts string arrays and character arrays with the 'rows' option, provided the inputs share the same number of columns.
How does union treat NaN values?⌄
All NaN values are considered equal. Sorted unions place them at the end, while stable unions keep the first-seen NaN.
Does GPU execution change the behaviour?⌄
No. When a provider does not implement a GPU kernel, RunMat automatically gathers inputs to the host, performs the union there, and returns host-resident outputs that match MATLAB semantics exactly.
What if the inputs have different shapes?⌄
Element-wise unions accept any shapes; both inputs are flattened column-major. Row-wise unions require matching column counts and two-dimensional inputs.
Can I mix data types?⌄
No. Inputs must belong to the same class (numeric/logical, complex, char, or string). Mixing classes produces a descriptive error.
Are scalar outputs returned as vectors?⌄
Scalars follow MATLAB's behaviour: a 1×1 union result is represented as a scalar double.
Do trailing spaces matter for character data?⌄
Yes. Character arrays treat every character, including trailing spaces, as significant—matching MATLAB's behaviour.
Is the 'legacy' flag supported?⌄
No. RunMat only implements the modern MATLAB semantics. Passing 'legacy' or 'R2012a' raises an error.
Related Array functions
Shape
cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how union is executed, line by line, in Rust.
- View the source for union 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.