RunMat
GitHub

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

NameTypeRequiredDefaultDescription
AAnyYesFirst input array.
BAnyYesSecond input array.
optionStringScalarVariadicOption tokens: 'rows'|'sorted'|'stable'.

Returns

NameTypeDescription
CAnyUnion values or rows.
iaNumericArrayIndices selecting contributions from A.
ibNumericArrayIndices selecting contributions from B.

Returned values from union depend on how many outputs the caller requests.

Errors

IdentifierWhenMessage
RunMat:union:LegacyOptionUnsupportedLegacy compatibility options are requested.union: the 'legacy' behaviour is not supported
RunMat:union:ConflictingOrderOptionsBoth 'sorted' and 'stable' options are provided.union: cannot combine 'sorted' with 'stable'
RunMat:union:UnknownOptionAn unsupported option token is provided.union: unrecognised option

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 where IA points to the elements in A that contribute to C and IB refers to the elements in B that only appear in B.
  • union(A, B, 'stable') preserves the first-seen order: unique values from A appear first, followed by new values appearing in B.
  • 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 =
     1

Preserving 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
     4

Union 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 =
     2

Working 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
    z

Union 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 =
     2

Using 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.

Sorting Sets

argsort · intersect · ismember · issorted · setdiff · sort · sortrows · unique

Shape

cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat

Creation

colon · eye · false · fill · inf · linspace · logspace · magic · meshgrid · nan · ones · peaks · rand · randi · randn · randperm · range · true · zeros

Indexing

find · ind2sub · sub2ind

Introspection

isempty · ismatrix · isscalar · isvector · length · ndims · numel · size

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how union is executed, line by line, in Rust.

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.