MATLAB - Set Operations


Advertisements


MATLAB provides various functions for set operations, like union, intersection and testing for set membership, etc.

The following table shows some commonly used set operations −

Sr.No. Function & Description
1

intersect(A,B)

Set intersection of two arrays; returns the values common to both A and B. The values returned are in sorted order.

2

intersect(A,B,'rows')

Treats each row of A and each row of B as single entities and returns the rows common to both A and B. The rows of the returned matrix are in sorted order.

3

ismember(A,B)

Returns an array the same size as A, containing 1 (true) where the elements of A are found in B. Elsewhere, it returns 0 (false).

4

ismember(A,B,'rows')

Treats each row of A and each row of B as single entities and returns a vector containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it returns 0 (false).

5

issorted(A)

Returns logical 1 (true) if the elements of A are in sorted order and logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is considered to be sorted if A and the output of sort(A) are equal.

6

issorted(A, 'rows')

Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output of sortrows(A) are equal.

7

setdiff(A,B)

Sets difference of two arrays; returns the values in A that are not in B. The values in the returned array are in sorted order.

8

setdiff(A,B,'rows')

Treats each row of A and each row of B as single entities and returns the rows from A that are not in B. The rows of the returned matrix are in sorted order.

The 'rows' option does not support cell arrays.

9

setxor

Sets exclusive OR of two arrays

10

union

Sets union of two arrays

11

unique

Unique values in array

Example

Create a script file and type the following code −

Live Demo
a = [7 23 14 15 9 12 8 24 35]
b = [ 2 5 7 8 14 16 25 35 27]
u = union(a, b)
i = intersect(a, b)
s = setdiff(a, b)

When you run the file, it produces the following result −

a =

    7   23   14   15    9   12    8   24   35

b =

    2    5    7    8   14   16   25   35   27

u =

    2    5    7    8    9   12   14   15   16   23   24   25   27   35

i =

    7    8   14   35

s =

    9   12   15   23   24

matlab_operators.htm


Advertisements
E-Books Store