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

setdiff — Return values present in the first input but absent from the second, with MATLAB-compatible ordering modes.

setdiff(A, B) returns unique values (or rows) that appear in A but not in B. It supports MATLAB-compatible 'sorted' and 'stable' ordering modes plus row-wise set differences.

Syntax

C = setdiff(A, B)
C = setdiff(A, B, option...)
[C, ia] = setdiff(A, B)
[C, ia] = setdiff(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
Values that appear in A but not in B.
ia
Type
NumericArray
Description
Indices selecting retained values/rows from A.
NameTypeDescription
CAnyValues that appear in A but not in B.
iaNumericArrayIndices selecting retained values/rows from A.

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

Errors

RunMat:setdiff:LegacyOptionUnsupported
When
Legacy compatibility options are requested.
Message
setdiff: the 'legacy' behaviour is not supported
RunMat:setdiff:ConflictingOrderOptions
When
Both 'sorted' and 'stable' options are provided.
Message
setdiff: cannot combine 'sorted' with 'stable'
RunMat:setdiff:UnknownOption
When
An unsupported option token is provided.
Message
setdiff: unrecognised option
IdentifierWhenMessage
RunMat:setdiff:LegacyOptionUnsupportedLegacy compatibility options are requested.setdiff: the 'legacy' behaviour is not supported
RunMat:setdiff:ConflictingOrderOptionsBoth 'sorted' and 'stable' options are provided.setdiff: cannot combine 'sorted' with 'stable'
RunMat:setdiff:UnknownOptionAn unsupported option token is provided.setdiff: unrecognised option
RunMat:setdiff:RowsColumnMismatch'rows' mode is used and column counts differ.setdiff: inputs must have the same number of columns when using 'rows'
RunMat:setdiff:UnsupportedInputTypeInput values cannot be converted into supported setdiff domains.setdiff: unsupported input type
RunMat:setdiff:NumericClassMismatchNumeric inputs have incompatible nondouble classes.setdiff: numeric inputs must have the same class, except double may be combined with one nondouble class
RunMat:setdiff:InvalidArgumentOption arguments are not string-like where required.setdiff: expected string option arguments
RunMat:setdiff:InternalInternal conversion/allocation/provider decode fails.setdiff: internal operation failed

Behavior

setdiff(A, B) flattens inputs column-major, removes duplicates, subtracts the values of B from A, and returns the remaining elements sorted ascending by default.

[C, IA] = setdiff(A, B) also returns indices so that C = A(IA).

setdiff(A, B, 'stable') preserves the first appearance order from A instead of sorting.

setdiff(A, B, 'rows') treats each row as an element. Inputs must share the same number of columns.

Character arrays, string arrays, logical arrays, numeric types, and complex values are all supported.

Legacy flags ('legacy', 'R2012a') are not supported; RunMat does not implement legacy flag semantics.

Types, placement and limitations

Element results follow A: a row-vector A gives a row result, otherwise a column. IA remains a column. Numeric and logical outputs retain A's class. A is never narrowed through the single comparison domain; supported mixed-class controls convert the B comparison operand instead. Unlike nondouble numeric classes are rejected. NaNs never match B or each other. Every NaN occurrence in A remains in C, including complex values or rows containing a NaN component.

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.

RunMat exact mixed-integer comparison

With double A and native integer B, RunMat compares their original numeric values exactly, including int64 and uint64 values beyond the exact double range. B is not rounded through double storage. C still contains selected original A values in double class; IA is a double column. This is a RunMat exactness policy for this mixed form, separate from output-class conversion.

The route uses indexed native comparisons for elements or rows and preserves the ordinary sorted/stable and distinct-NaN rules. Managed finite host allocation is not supported for this route; those calls fail before provider work or gathering because complete selector scratch and retained-output ownership is not available.

Examples

Finding values exclusive to the first numeric vector

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

Expected output:

C =
     5
IA =
     1

Preserving input order with 'stable'

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

Expected output:

C =
     2
IA =
     2

Working with rows of numeric matrices

A = [1 2; 3 4; 1 2];
B = [3 4; 5 6];
[C, IA] = setdiff(A, B, 'rows')

Expected output:

C =
     1     2
IA =
     1

Computing set difference for character data

A = ['m','z'; 'm','a'];
B = ['a','x'; 'm','a'];
[C, IA] = setdiff(A, B)

Expected output:

C = 'z'; IA = 3

Subtracting string arrays by row

A = ["alpha" "beta"; "gamma" "beta"];
B = ["gamma" "beta"; "delta" "beta"];
[C, IA] = setdiff(A, B, 'rows', 'stable')

Expected output:

C =
  1x2 string array
    "alpha"    "beta"
IA =
     1

Using setdiff with GPU arrays

G = gpuArray([10 4 6 4]);
H = gpuArray([6 4 2]);
C = setdiff(G, H)

Expected output:

C =
    10

Retain A precision, row orientation and every NaN

A = [1+eps(1) 2 NaN NaN]; B = single([2 NaN]); [C,IA] = setdiff(A,B); L = setdiff(logical([1 0 1]),false);

Compare a wide integer without rounding it into A

A = [9007199254740992 1.5 NaN]; B = [0x0020000000000001u64 0u64]; [C,IA] = setdiff(A,B,'stable');

Using setdiff with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how setdiff changes the result.

Run a small setdiff example, explain the result, then change one input and compare the output.

FAQ

What ordering does setdiff use by default?⌄

Results are sorted ascending. Specify 'stable' to preserve the first appearance order from the first input.

How are the index outputs defined?⌄

IA points to the positions in A that correspond to each element (or row) returned in C, using MATLAB's one-based indexing.

Can I combine 'rows' with 'stable'?⌄

Yes. 'rows' can be paired with either 'sorted' (default) or 'stable'. Other option combinations that conflict (e.g. 'sorted' with 'stable') are rejected.

Does setdiff remove NaN values from A when they exist in B?⌄

Element results follow A: a row-vector A gives a row result, otherwise a column. IA remains a column. Numeric and logical outputs retain A's class. A is never narrowed through the single comparison domain; supported mixed-class controls convert the B comparison operand instead. Unlike nondouble numeric classes are rejected. NaNs never match B or each other. Every NaN occurrence in A remains in C, including complex values or rows containing a NaN component.

Are complex numbers supported?⌄

Absolutely. Complex values use MATLAB's ordering rules (magnitude, then real part, then imaginary part) for the sorted output.

Does GPU execution change the results?⌄

Element results follow A: a row-vector A gives a row result, otherwise a column. IA remains a column. Numeric and logical outputs retain A's class. A is never narrowed through the single comparison domain; supported mixed-class controls convert the B comparison operand instead. Unlike nondouble numeric classes are rejected. NaNs never match B or each other. Every NaN occurrence in A remains in C, including complex values or rows containing a NaN component. 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 happens if the inputs have different classes?⌄

Supported numeric inputs retain A's class, including when double is combined with single or one integer class. Unlike nondouble numeric classes are rejected.

Can I request 'legacy' behaviour?⌄

No. RunMat does not implement legacy flag semantics. Passing 'legacy' or 'R2012a' results in an error.

Related Array functions

Sorting Sets

argsort · intersect · ismember · ismembertol · issorted · issortedrows · setxor · sort · sortrows · union · 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 setdiff is executed, line by line, in Rust.

  • View the source for setdiff 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
  • RunMat exact mixed-integer comparison
  • Examples
  • Finding values exclusive to the first numeric vector
  • Preserving input order with 'stable'
  • Working with rows of numeric matrices
  • Computing set difference for character data
  • Subtracting string arrays by row
  • Using setdiff with GPU arrays
  • Retain A precision, row orientation and every NaN
  • Compare a wide integer without rounding it into A
  • Using setdiff with coding agents
  • FAQ
  • Related Array functions
  • Sorting Sets
  • Accumulation
  • Shape
  • Creation
  • Combinatorics
  • Binning
  • Indexing
  • Grouping
  • Introspection
  • Source you can read
  • About RunMat