RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.1, Nov 17, 2026

RunMat® is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • argsort
    • intersect
    • ismember
    • ismembertol
    • issorted
    • issortedrows
    • setdiff
    • setxor
    • sort
    • sortrows
    • union
    • unique

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

A
Type
Any
Required
Yes
Description
First input array.
B
Type
Any
Required
Yes
Description
Second input array.
option
Type
StringScalar
Required
Variadic
Description
Option tokens: 'rows'|'sorted'|'stable'.
NameTypeRequiredDefaultDescription
AAnyYes—First input array.
BAnyYes—Second input array.
optionStringScalarVariadic—Option tokens: 'rows'|'sorted'|'stable'.

Returns

C
Type
Any
Description
Union values or rows.
ia
Type
NumericArray
Description
Indices selecting contributions from A.
ib
Type
NumericArray
Description
Indices selecting contributions from B.
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

RunMat:union:LegacyOptionUnsupported
When
Legacy compatibility options are requested.
Message
union: the 'legacy' behaviour is not supported
RunMat:union:ConflictingOrderOptions
When
Both 'sorted' and 'stable' options are provided.
Message
union: cannot combine 'sorted' with 'stable'
RunMat:union:UnknownOption
When
An unsupported option token is provided.
Message
union: unrecognised option
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
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:UnsupportedInputTypeInput values cannot be converted into supported union domains.union: unsupported input type
RunMat:union:NumericClassMismatchNumeric inputs have incompatible nondouble classes.union: numeric inputs must have the same class, except double may be combined with one nondouble class
RunMat:union:InvalidArgumentOption arguments are not string-like where required.union: expected string option arguments
RunMat:union:InternalInternal conversion/allocation/provider decode fails.union: internal operation failed

Behavior

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.

Types, placement and limitations

Element results are rows when both inputs are row vectors, and columns otherwise. Index outputs remain columns. Matching numeric classes are preserved. Combining double with single or one integer class preserves the nondouble class; unlike nondouble numeric classes are rejected. Logical inputs currently produce double values. Each NaN occurrence is distinct, including repeated NaNs in the same input. Sorted output places them last; stable output preserves their occurrence order.

Resident execution

These operations are eager fusion boundaries, not elementwise kernels or reductions, and do not broadcast. Provider availability does not imply a device-native sorting or set kernel: current providers may stage host work. An unsupported input can use exact host fallback before provider work starts. Errors after an attempt, including cancellation, are returned without repeating the operation on the host. Supported resident outputs return to their owning provider; predicates and all-indices cells have the host placement described above. Distributed execution is not supported.

Examples

Combining Two Numeric Vectors

A = [5 7 1];
B = [3 1 1];
[C, IA, IB] = union(A, B)

Preserving Input Order with 'stable'

A = [5 7 1];
B = [3 2 4];
C = union(A, B, 'stable')

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)

Preserve distinct NaNs and row orientation

A = [NaN NaN 1]; B = [1 NaN]; [C,IA,IB] = union(A,B); [S,SA,SB] = union(A,B,'stable');

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?⌄

Element results are rows when both inputs are row vectors, and columns otherwise. Index outputs remain columns. Matching numeric classes are preserved. Combining double with single or one integer class preserves the nondouble class; unlike nondouble numeric classes are rejected. Logical inputs currently produce double values. Each NaN occurrence is distinct, including repeated NaNs in the same input. Sorted output places them last; stable output preserves their occurrence order.

Does GPU execution change the behaviour?⌄

Element results are rows when both inputs are row vectors, and columns otherwise. Index outputs remain columns. Matching numeric classes are preserved. Combining double with single or one integer class preserves the nondouble class; unlike nondouble numeric classes are rejected. Logical inputs currently produce double values. Each NaN occurrence is distinct, including repeated NaNs in the same input. Sorted output places them last; stable output preserves their occurrence order. These operations are eager fusion boundaries, not elementwise kernels or reductions, and do not broadcast. Provider availability does not imply a device-native sorting or set kernel: current providers may stage host work. An unsupported input can use exact host fallback before provider work starts. Errors after an attempt, including cancellation, are returned without repeating the operation on the host. Supported resident outputs return to their owning provider; predicates and all-indices cells have the host placement described above. Distributed execution is not supported.

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

Sorting Sets

argsort · intersect · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · unique

Accumulation

accumarray

Shape

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

Creation

colon · createArray · empty · eye · false · full · inf · int16.empty · int32.empty · int64.empty · int8.empty · linspace · logspace · magic · meshgrid · nan · ndgrid · nonzeros · ones · peaks · rand · randi · randn · randperm · range · sparse · spdiags · speye · spones · sprand · true · uint16.empty · uint32.empty · uint64.empty · uint8.empty · zeros

Combinatorics

combinations · nchoosek · perms

Binning

discretize

Indexing

find · ind2sub · sub2ind

Grouping

findgroups · groupcounts · grp2idx · splitapply

Introspection

height · iscolumn · isempty · ismatrix · isrow · isscalar · isvector · length · ndims · numel · size · width

Source you can read

Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • Behavior
  • Types, placement and limitations
  • Resident execution
  • Examples
  • Combining Two Numeric Vectors
  • Preserving Input Order with 'stable'
  • Union of Matrix Rows
  • Working with Character Arrays
  • Union on GPU Data
  • Preserve distinct NaNs and row orientation
  • Using union with coding agents
  • FAQ
  • Related Array functions
  • Sorting Sets
  • Accumulation
  • Shape
  • Creation
  • Combinatorics
  • Binning
  • Indexing
  • Grouping
  • Introspection
  • Source you can read
  • About RunMat