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)
Where:
Ais the input array.Bis the output array containing unique elements ofA.
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
uniquefunction is called with the arrayAas its input. Theuniquefunction returns unique elements ofAthat are stored in an arrayB.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