intersect — Return common elements or rows across arrays in MATLAB and RunMat.
intersect(A, B) computes the set intersection of A and B. Default ordering and optional index outputs follow MATLAB semantics.
Syntax
C = intersect(A, B)
C = intersect(A, B, option...)
[C, ia] = intersect(A, B)
[C, ia] = intersect(A, B, option...)
[C, ia, ib] = intersect(A, B)
[C, ia, ib] = intersect(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'.
Returns
C- Type
Any- Description
- Intersection values or rows.
ia- Type
NumericArray- Description
- Indices selecting matching elements/rows in A.
ib- Type
NumericArray- Description
- Indices selecting matching elements/rows in B.
Returned values from intersect depend on how many outputs the caller requests.
Errors
RunMat:intersect:LegacyOptionUnsupported- When
- Legacy compatibility options are requested.
- Message
intersect: the 'legacy' behaviour is not supported
RunMat:intersect:ConflictingOrderOptions- When
- Both 'sorted' and 'stable' options are provided.
- Message
intersect: cannot combine 'sorted' with 'stable'
RunMat:intersect:UnknownOption- When
- An unsupported option token is provided.
- Message
intersect: unrecognised option
Behavior
intersect(A, B) flattens both inputs column-major, removes duplicates, and returns the sorted intersection.
[C, IA, IB] = intersect(A, B) also returns index vectors so that C = A(IA) and C = B(IB).
intersect(A, B, 'stable') preserves the first appearance order from A.
intersect(A, B, 'rows') treats each row as an element. Inputs must share the same number of columns.
Supported character, string, logical and numeric inputs are accepted; numeric mixing and class limitations are described below.
Legacy flags such as '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. NaN values never match, so intersections do not contain NaNs. A complex value or row with any NaN component likewise does not match.
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
Finding common values in numeric vectors
A = [5 7 5 1];
B = [7 1 3];
[C, IA, IB] = intersect(A, B)Preserving input order with 'stable'
A = [4 2 4 1 3];
B = [3 4 5 1];
C = intersect(A, B, 'stable')Intersecting matrix rows
A = [1 2; 3 4; 1 2];
B = [2 3; 1 2];
[C, IA, IB] = intersect(A, B, 'rows')Expected output:
C =
1 2
IA =
1
IB =
2Working with strings and character arrays
names1 = ["apple" "orange" "pear"];
names2 = ["pear" "grape" "orange"];
[common, IA, IB] = intersect(names1, names2, 'stable')Using intersect on GPU arrays
G = gpuArray([10 4 6 4]);
H = gpuArray([6 4 2]);
result = intersect(G, H)Exclude NaNs from intersections
A = [NaN 2 NaN 1]; B = [NaN;1;2]; [C,IA,IB] = intersect(A,B); R = intersect(A,B.');Using intersect with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how intersect changes the result.
Run a small intersect example, explain the result, then change one input and compare the output.
FAQ
Does intersect keep duplicate values?⌄
No. MATLAB and RunMat return each common value at most once. Use other logic (such as logical indexing) if you need multiset behavior.
What is the default ordering?⌄
intersect sorts results ascending by default. Specify 'stable' to preserve the input order from A.
Can I intersect rows that contain strings?⌄
Yes. String arrays support both element and row intersections. When using 'rows', the inputs must have the same number of columns.
Are NaN values considered equal?⌄
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. NaN values never match, so intersections do not contain NaNs. A complex value or row with any NaN component likewise does not match.
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 · ismember · ismembertol · issorted · issortedrows · setdiff · setxor · sort · sortrows · union · unique
Accumulation
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
Binning
Grouping
Source you can read
Every RunMat function's source is public. Read exactly how intersect is executed, line by line, in Rust.
- View the source for intersect 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.