Deleting duplicates from an array in MATLAB

In MATLAB, managing arrays efficiently is a common task for various computational and analytical purposes. Arrays may often contain duplicate elements, which can interfere with analyses or computations. To address this, MATLAB provides a straightforward method to remove duplicates from an array using the unique function. This Answer will guide us through removing duplicates from an array in MATLAB, providing examples and explanations.

Understanding the unique function

The unique function in MATLAB is designed to identify and remove duplicate elements from an array. It returns unique elements of an array, sorted in ascending order by default. The syntax of the unique function is as follows:

[B] = unique(A)
Syntax of the unique() function

Where:

  • A is the input array.

  • B is the output array containing unique elements of A.

Basic usage of the unique function

Let’s consider a simple example to demonstrate how to use the unique function to remove duplicates from an array:

A = [5 2 9 5 2 8 9];
[B] = unique(A);
disp(B);

Explanation

  • Line 1: We declare and initialize an array A.

  • Line 2: The unique function is called with the array A as its input. The unique function returns unique elements of A that are stored in an array B.

  • Line 3: We display the array B.

Conclusion

The unique function in MATLAB provides a convenient and efficient way to remove duplicates from arrays, which is a common requirement in various computational tasks. By understanding the syntax and behavior of the unique function, users can easily manipulate arrays to extract only the unique elements while retaining crucial indexing information.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved