Octave:Sets

From AIMSWiki

Table of contents


Octave implements some 'very' basic set operations. Sets are implemented as ordered vectors and, for this reason, the set functions may also be useful for

  • sorting and
  • finding unique elements in

a vector.

Creating a set

You can create an empty set by using an empty vector:

octave:1> A = [];

This is often a good place to start and you can use the functions for manipulating sets (see the next section) to add elements to this.

You can also create a set from a vector using

octave:2> A = create_set(x);

Here, x is a vector or matrix and the result, stored in A contains unique values from x sorted in ascending order. For example,

octave:3> create_set([1, 2; 3, 4; 4, 2])
ans =

  1  2  3  4

Manipulating sets

The three set operations union, A\cup B, intersection, A\cap B and complement, \overline{A} are implemented in Octave and behaves in the normal way. The commands for these functions are

  • union(a, b) returns a set of elements that are in at least one of a and b
  • intersection(a, b) returns the elements that are in both a and b
  • complement(a, b) returns the elements from b that are not in a (this is actually the set difference, B / A, but can be thought of as the complement of A if B is the universe of elements)

The following examples illustrate the functions.

octave:4> u = create_set([1, 10, 5, 2, 4])
u =

   1   2   4   5  10

octave:5> v = create_set([3, 4, 5, 6])
v =

  3  4  5  6

octave:6> union(u, v)
ans =

   1   2   3   4   5   6  10

octave:7> intersection(u, v)
ans =

  4  5

octave:8> complement(u, [1:10])
ans =

  3  6  7  8  9