# 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:

Function | Description |
---|---|

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

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. |

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). |

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). |

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. |

issorted(A, 'rows') | Returns logical 1 (true) if the rows of two-dimensional matrix A are 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. |

setdiff(A,B) | Set difference of two arrays; returns the values in A that are not in B. The values in the returned array are in sorted order. |

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. |

setxor | Set exclusive OR of two arrays |

union | Set union of two arrays |

unique | Unique values in array |

## Example

Create a script file and type the following code:

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 = Columns 1 through 11 2 5 7 8 9 12 14 15 16 23 24 Columns 12 through 14 25 27 35 i = 7 8 14 35 s = 9 12 15 23 24