Set intersection of two arrays (2024)

Set intersection of two arrays

collapse all in page

Syntax

C = intersect(A,B)

C = intersect(A,B,setOrder)

C = intersect(A,B,___,'rows')

C = intersect(A,B,'rows',___)

[C,ia,ib]= intersect(___)

[C,ia,ib]= intersect(A,B,'legacy')

[C,ia,ib]= intersect(A,B,'rows','legacy')

Description

example

C = intersect(A,B) returns the data common to both A and B, with no repetitions. C is in sorted order.

  • If A and B are tables or timetables, then intersect returns the set of rows common to both tables. For timetables, intersect takes row times into account to determine equality, and sorts the output timetable C by row times.

example

C = intersect(A,B,setOrder) returns C in a specific order. setOrder can be 'sorted' or 'stable'.

C = intersect(A,B,___,'rows') and C = intersect(A,B,'rows',___) treat each row of A and each row of B as single entities and return the rows common to both A and B, with no repetitions. You must specify A and B and optionally can specify setOrder.

The 'rows' option does not support cell arrays, unless one of the inputs is either a categorical array or a datetime array.

example

[C,ia,ib]= intersect(___) also returns index vectors ia and ib using any of the previous syntaxes.

  • Generally, C = A(ia) and C = B(ib).

  • If the 'rows' option is specified, then C = A(ia,:) and C = B(ib,:).

  • If A and B are tables or timetables, then C = A(ia,:) and C = B(ib,:).

example

[C,ia,ib]= intersect(A,B,'legacy') and [C,ia,ib]= intersect(A,B,'rows','legacy') preserve the behavior of the intersect function from R2012b and prior releases.

The 'legacy' option does not support categoricalarrays, datetime arrays, duration arrays, tables, or timetables.

Examples

collapse all

Intersection of Two Vectors

Open Live Script

Create two vectors that have some values in common.

A = [7 1 7 7 4]; B = [7 0 4 4 0];

Find the values common to both A and B.

C = intersect(A,B)
C = 1×2 4 7

Intersection of Two Tables

Open Live Script

Create two tables with rows in common.

A = table([1:5]',categorical({'A';'B';'C';'D';'E'}),logical([0;1;0;1;0]))
A=5×3 table Var1 Var2 Var3 ____ ____ _____ 1 A false 2 B true 3 C false 4 D true 5 E false
B = table([1:2:10]',categorical({'A';'C';'E';'G';'I'}),logical(zeros(5,1)))
B=5×3 table Var1 Var2 Var3 ____ ____ _____ 1 A false 3 C false 5 E false 7 G false 9 I false

Find the rows common to both A and B.

C = intersect(A,B)
C=3×3 table Var1 Var2 Var3 ____ ____ _____ 1 A false 3 C false 5 E false

Intersection of Two Vectors and Their Indices

Open Live Script

Create two vectors with values in common.

A = [7 1 7 7 4]; B = [7 0 4 4 0];

Find the values common to both A and B, as well as the index vectors ia and ib, such that C = A(ia) and C = B(ib).

[C,ia,ib] = intersect(A,B)
C = 1×2 4 7
ia = 2×1 5 1
ib = 2×1 3 1

Intersection of Two Tables and Their Indices

Open Live Script

Create a table, A, of gender, age, and height for five people.

A = table(categorical({'M';'M';'F';'M';'F'}),...[27;52;31;46;35],[74;68;64;61;64],...'VariableNames',{'Gender' 'Age' 'Height'},...'RowNames',{'Ted' 'Fred' 'Betty' 'Bob' 'Judy'})
A=5×3 table Gender Age Height ______ ___ ______ Ted M 27 74 Fred M 52 68 Betty F 31 64 Bob M 46 61 Judy F 35 64 

Create a table, B, with rows in common with A.

B = table(categorical({'F';'M';'F';'F'}),...[31;47;35;23],[64;68;62;58],...'VariableNames',{'Gender' 'Age' 'Height'},...'RowNames',{'Meg' 'Joe' 'Beth' 'Amy'})
B=4×3 table Gender Age Height ______ ___ ______ Meg F 31 64 Joe M 47 68 Beth F 35 62 Amy F 23 58 

Find the rows common to both A and B, as well as the index vectors ia and ib, such that C = A(ia,:) and C = B(ib,:).

[C,ia,ib] = intersect(A,B)
C=1×3 table Gender Age Height ______ ___ ______ Betty F 31 64 
ia = 3
ib = 1

Two rows that have the same values, but different names, are considered equal. Therefore, we discover that Betty, A(3,:), and Meg, B(1,:) have the same gender, age, and height.

Intersection of Rows in Two Matrices

Open Live Script

Create two matrices with rows in common.

A = [2 2 2; 0 0 1; 1 2 3; 1 1 1];B = [1 2 3; 2 2 2; 2 2 0];

Find the rows common to both A and B as well as the index vectors ia and ib, such that C = A(ia,:) and C = B(ib,:).

[C,ia,ib] = intersect(A,B,'rows')
C = 2×3 1 2 3 2 2 2
ia = 2×1 3 1
ib = 2×1 1 2

A and B do not need to have the same number of rows, but they must have the same number of columns.

Intersection with Specified Output Order

Open Live Script

Use the setOrder argument to specify the ordering of the values in C.

Specify 'stable' if you want the values in C to have the same order as in A.

A = [7 1 7 7 4]; B = [7 0 4 4 0];[C,ia,ib] = intersect(A,B,'stable')
C = 1×2 7 4
ia = 2×1 1 5
ib = 2×1 1 3

Alternatively, you can specify 'sorted' order.

[C,ia,ib] = intersect(A,B,'sorted')
C = 1×2 4 7
ia = 2×1 5 1
ib = 2×1 3 1

Intersection of Vectors Containing NaNs

Open Live Script

Create two vectors containing NaN.

A = [5 NaN NaN]; B = [5 NaN NaN];

Find the values common to both A and B.

C = intersect(A,B)
C = 5

intersect treats NaN values as distinct.

Cell Array of Character Vectors with Trailing White Space

Open Live Script

Create a cell array of character vectors, A.

A = {'dog','cat','fish','horse'};

Create a cell array of character vectors, B, where some of the vectors have trailing white space.

B = {'dog ','cat','fish ','horse'};

Find the character vectors common to both A and B.

[C,ia,ib] = intersect(A,B)
C = 1x2 cell {'cat'} {'horse'}
ia = 2×1 2 4
ib = 2×1 2 4

intersect treats trailing white space in cell arrays of character vectors as distinct characters.

Intersection of Arrays of Different Classes and Shapes

Open Live Script

Create a column vector character array.

A = ['A';'B';'C'], class(A)
A = 3x1 char array 'A' 'B' 'C'
ans = 'char'

Create a 2-by-3 matrix containing elements of numeric type double.

B = [65 66 67;68 69 70], class(B)
B = 2×3 65 66 67 68 69 70
ans = 'double'

Find the values common to both A and B.

[C,ia,ib] = intersect(A,B)
C = 3x1 char array 'A' 'B' 'C'
ia = 3×1 1 2 3
ib = 3×1 1 3 5

intersect interprets B as a character array and returns a character array, C.

class(C)
ans = 'char'

Intersection of Char and Cell Array of Character Vectors

Open Live Script

Create a character vector containing animal names that have three letters.

A = ['dog';'cat';'fox';'pig'];class(A)
ans = 'char'

Create a cell array of character vectors containing animal names of varying lengths.

B = {'cat','dog','fish','horse'};class(B)
ans = 'cell'

Find the character vectors common to both A and B.

C = intersect(A,B)
C = 2x1 cell {'cat'} {'dog'}

The result, C, is a cell array of character vectors.

class(C)
ans = 'cell'

Preserve Legacy Behavior of intersect

Open Live Script

Use the 'legacy' flag to preserve the behavior of intersect from R2012b and prior releases in your code.

Find the intersection of A and B with the current behavior.

A = [7 1 7 7 4]; B = [7 0 4 4 0];[C1,ia1,ib1] = intersect(A,B)
C1 = 1×2 4 7
ia1 = 2×1 5 1
ib1 = 2×1 3 1

Find the unique elements of A and preserve the legacy behavior.

[C2,ia2,ib2] = intersect(A,B,'legacy')
C2 = 1×2 4 7
ia2 = 1×2 5 4
ib2 = 1×2 4 1

Input Arguments

collapse all

setOrderOrder flag
'sorted' (default) | 'stable'

Order flag, specified as 'sorted' or 'stable', indicates the order of the values (or rows) in C.

FlagDescription
'sorted'

The values (or rows) in C return in sorted order as returned by sort.

Example

C = intersect([7 0 1 5],[0 2 7 5],'sorted')
C = 0 5 7
'stable'

The values (or rows) in C return in the same order as they appear in A.

Example

C = intersect([7 0 1 5],[0 2 7 5],'stable')
C = 7 0 5

Data Types: char | string

Output Arguments

collapse all

C — Data common to A and B
vector | matrix | table | timetable

Data common to A and B, returned as a vector, matrix, or table. If the inputs A and B are tables or timetables, then the order of the variables in C is the same as the order of the variables in A.

The following describes the shape of C when the inputs are vectors or matrices and when the 'legacy' flag is not specified:

  • If the 'rows' flag is not specified, then C is a column vector unless both A and B are row vectors, in which case C is a row vector.

  • If the 'rows' flag is specified, then C is a matrix containing the rows in common from A and B.

The class of the inputs A and B determinesthe class of C:

  • If the class of A and B arethe same, then C is the same class.

  • If you combine a char or nondoublenumeric class with double, then C isthe same class as the nondouble input.

  • If you combine a logical classwith double, then C is double.

  • If you combine a cell array of character vectors with char,then C is a cell array of character vectors.

  • If you combine a categorical array with a charactervector, cell array of character vectors, or string, then C isa categorical array.

  • If you combine a datetime array with a cell arrayof date character vectors or single date character vector, then C isa datetime array.

  • If you combine a string array with a character vectoror cell array of character vectors, then C is astring array.

ia — Index to A
column vector

Index to A, returned as a column vector when the 'legacy' flag is not specified. ia identifies the values (or rows) in A that are common to B. If there is a repeated value (or row) in A, then ia contains the index to the first occurrence of the value (or row).

ib — Index to B
column vector

Index to B, returned as a column vector when the 'legacy' flag is not specified. ib identifies the values (or rows) in B that are common to A. If there is a repeated value (or row) in B, then ib contains the index to the first occurrence of the value (or row).

Tips

  • To find the intersection with respect to a subset of variables from a table or timetable, you can use column subscripting. For example, you can use intersect(A(:,vars),B(:,vars)), where vars is a positive integer, a vector of positive integers, a variable name, a cell array of variable names, or a logical vector. Alternatively, you can use vartype to create a subscript that selects variables of a specified type.

Extended Capabilities

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced before R2006a

See Also

unique | union | ismember | issorted | setdiff | setxor | sort

Topics

  • Combine Categorical Arrays

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Set intersection of two arrays (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

Contact your local office

Set intersection of two arrays (2024)

FAQs

How do you find the intersection of two arrays? ›

We can use O(nlogn) sorting algorithms like heap sort, quick sort, or merge sort. We run a loop from i = 0 to m - 1 and search each element X[i] in the sorted array Y[] using binary search. Whenever we find an element common to both X[] and Y[], i.e., X[i] == Y[j], we add it to the output list intersection[].

What is the program to find intersection of two arrays in JavaScript? ›

Each element of the first array is compared with the second array using the indexOf() method. The arr2. indexOf(x) method searches arr2 and returns the position of the first occurrence of arr1 . If the value cannot be found, it returns -1.

How to get common elements from two arrays in JavaScript? ›

Creating a new JavaScript Object
  1. Create an empty object and loop through the first array.
  2. Check if the elements from the first array exist in the object or not. ...
  3. Loop through the second array and check if elements in the second array exist on created object.
  4. If an element exists then return true else return false.
May 31, 2024

What is the intersection function in JavaScript? ›

js | intersect() Function. The intersect() function is used to remove the value in the main collection which is not present in the given collection.

What is the intersection between two sorted arrays? ›

In the optimal approach, we will use 2 pointers, to merge the intersection of the 2 arrays in a merge-sort-based manner. The Algorithm is : Use two index variables first and second, initial values of both to be set to 0. If arr1[first] is smaller than arr2[second] then increment first.

What is the formula for the intersection of two sets? ›

The intersection of sets formula gives the total number of elements in a set (which is called the cardinal number of the set). It says, for the two finite sets A and B, n(A ∩ B) = n(A) + n(B) – n(A ∪ B).

How do you find two intersections? ›

Here's a step-by-step process:
  1. Write down the equations of the two functions, f(x) and g(x).
  2. Set the two functions equal to each other: f(x) = g(x).
  3. Solve the equation for x. ...
  4. For each x-value found in step 3, plug it back into either f(x) or g(x) to find the corresponding y-value.

How to find the intersection of two lists in Java? ›

First, we remove the duplicated elements with distinct. Then, we use the filter to select the elements that are also contained in the otherList. Finally, we convert our output with a Collector. The intersection should contain each common element only once.

How to get intersection of two sets in JavaScript? ›

Using the has() & filter() Method: We check if the element is present in set1 also then we are going to add that element to the new set. Example 2: In this example, we will see the intersection of sets by using the filter() method. We have also used the spread operator for separating the element.

How to use filter() to find the intersection of two arrays in JavaScript? ›

We can use the filter() and includes() methods to perform the intersection on two arrays. The filter() method accepts a function as its argument and applies it to each element in the array. The function should return a boolean, true or false, indicating whether the element should be included in the new array.

How to find the intersection of three arrays in Java? ›

A simple solution is to first find the intersection of two arrays and store the intersection in a temporary array, then find the intersection of the third array and temporary array. Initialize both pointers i and j to 0, and an empty list common.

How to find the difference between two arrays in JavaScript? ›

How to Get the Difference Between Two Arrays in JavaScript ?
  1. Approach 1: Using the filter() and includes() methods.
  2. Approach 2: Using for Loop and indexOf() Method.
  3. Approach 3: Using Set and filter() Method.
  4. Approach 4: Using reduce() and includes() Methods.
  5. Approach 6: Using Array.filter() and Array.every() Methods.
May 27, 2024

What is intersection of sets examples? ›

For example: The intersection of the sets {1, 2, 3} and {2, 3, 4} is {2, 3}. The number 9 is not in the intersection of the set of prime numbers {2, 3, 5, 7, 11, ...} and the set of odd numbers {1, 3, 5, 7, 9, 11, ...}, because 9 is not prime.

How does set intersection work? ›

As defined above, the intersection of two sets A and B is the set of all those elements which are common to both A and B. Symbolically, we can represent the intersection of A and B as A ∩ B.

How to find the intersection of two strings in JavaScript? ›

1 Answer. Convert one of the strings ( search ) to a RegExp character set. Use the RegExp with String#match on the other string ( select ). Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.

How do you find the intersection of two lists? ›

Example -
  1. # Python program to get the intersection.
  2. # of two lists using set() and intersection()
  3. def intersection_list(list1, list2):
  4. return set(list1).intersection(list2)
  5. list1 = [40, 90, 11, 58, 31, 66, 28, 54, 79]
  6. list2 = [58, 90, 54, 31, 45, 11, 66, 28, 26]
  7. print(intersection_list(list1, list2))

How do you find the intersection of two values? ›

In general, to find intersection between two curves y=f(x) and y=g(x), you would look for solutions of f(x)=g(x) as you showed in your example. To find the intersections between y=|f(x)| and y=|g(x)|, you should thus solve |f(x)|=|g(x)|, or equivalently, f2(x)=g2(x).

How do you find the intersection of two circles? ›

To do this, you need to work out the radius and the centre of each circle. If the sum of the radii and the distance between the centres are equal, then the circles touch externally. If the difference between the radii and the distance between the centres are equal, then the circles touch internally.

How do you find the intersection of two coordinates? ›

The x-coordinate of the point of intersection is found by the ratio ( b 1 c 2 − b 2 c 1 ) / ( a 1 b 2 − a 2 b 1 ) , while the y-coordinate of the point of intersection is found by the ratio ( a 2 c 1 − a 1 c 2 ) / ( a 1 b 2 − a 2 b 1 ) .

Top Articles
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 6341

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.