TExcelTAD
Home › MATLAB / Octave › Sets & unique

Sets & unique

MATLAB has a family of set functions that treat arrays as sets of values: removing duplicates, finding common or different elements, and testing membership. They work with numbers and with cell arrays of text, and they return sorted results by default.

unique

unique(v) returns the distinct values, sorted. Two extra outputs connect the original array and the result:

matlab · try it yourself
rolls = [4 2 6 2 4 4 1 6];
u = unique(rolls)
[u, firstIdx, map] = unique(rolls);
disp(firstIdx')        % positions in rolls where each unique value appears
disp(map')             % for each roll, its position in u
u =

   1   2   4   6

   7   2   1   3
   3   2   4   2   3   3   1   4

u(map) rebuilds the original array, and rolls(firstIdx) equals u. The value 4, for example, appears at positions 1, 5 and 6; firstIdx reports position 1, the first occurrence. (Very old MATLAB versions returned the last occurrence; pass 'first' or 'last' if you depend on it.)

Pass 'stable' to keep the original order instead of sorting:

matlab · try it yourself
visits = {'home', 'shop', 'home', 'cafe', 'shop', 'park'};
disp(strjoin(unique(visits), ', '))
disp(strjoin(unique(visits, 'stable'), ', '))
cafe, home, park, shop
home, shop, cafe, park

Counting occurrences

unique combined with accumarray (or histc) counts how often each value appears:

matlab · try it yourself
rolls = [4 2 6 2 4 4 1 6];
[vals, ~, map] = unique(rolls);
counts = accumarray(map(:), 1)';
fprintf('value %d: count %d\n', [vals; counts]);
[~, k] = max(counts);
fprintf('most common: %d\n', vals(k));
value 1: count 1
value 2: count 2
value 4: count 3
value 6: count 2
most common: 4

Union, intersection, difference

Function Returns
union(a, b) Values in a or b
intersect(a, b) Values in both
setdiff(a, b) Values in a but not in b
setxor(a, b) Values in exactly one of them
matlab · try it yourself
mathClub = {'Ana', 'Ben', 'Chen', 'Dita'};
chessClub = {'Chen', 'Eli', 'Ana', 'Fay'};
fprintf('either:  %s\n', strjoin(union(mathClub, chessClub), ', '));
fprintf('both:    %s\n', strjoin(intersect(mathClub, chessClub), ', '));
fprintf('only math: %s\n', strjoin(setdiff(mathClub, chessClub), ', '));
fprintf('only one:  %s\n', strjoin(setxor(mathClub, chessClub), ', '));
disp(union([3 1 2], [2 5]))
either:  Ana, Ben, Chen, Dita, Eli, Fay
both:    Ana, Chen
only math: Ben, Dita
only one:  Ben, Dita, Eli, Fay
   1   2   3   5

intersect and setdiff can also return index outputs that tell you where the values came from.

Membership: ismember

ismember(a, s) returns a logical array: for each element of a, is it in the set s? The second output gives its position in s (0 if absent). This is how you look things up in a list:

matlab · try it yourself
allowed = [2 3 5 7 11];
disp(ismember([1 2 3 4 5], allowed))

codes = {'DE', 'FR', 'IT'};
names = {'Germany', 'France', 'Italy'};
query = {'IT', 'ES', 'DE'};
[found, where] = ismember(query, codes);
for k = 1:numel(query)
    if found(k)
        fprintf('%s -> %s\n', query{k}, names{where(k)});
    else
        fprintf('%s -> unknown\n', query{k});
    end
end
  0  1  1  0  1
IT -> Italy
ES -> unknown
DE -> Germany

Unique rows

With the 'rows' option, set functions treat each row of a matrix as one element. That's useful for coordinate pairs or records:

matlab · try it yourself
points = [1 2; 3 4; 1 2; 0 0; 3 4];
disp(unique(points, 'rows'))
disp(ismember([3 4; 9 9], points, 'rows')')
   0   0
   1   2
   3   4
  1  0

Test yourself

What does unique([3 1 3 2 1]) return?

  1. [3 1 2]
  2. [1 2 3]
  3. [1 1 2 3 3]
  4. 3

Which function gives the elements of a that are NOT in b?

  1. intersect(a, b)
  2. setdiff(a, b)
  3. union(a, b)
  4. setxor(a, b)

What is ismember(5, [1 5 9])?

  1. 2
  2. true (1)
  3. false (0)
  4. 5