How to detect duplicate values and its indices within an array in MATLAB?
Last Updated :
11 Oct, 2021
In this article, we will discuss how to find duplicate values and their indices within an array in MATLAB. It can be done using unique(), length(), setdiff(), and numel() functions that are illustrated below:
Using Unique()
Unique(A) function is used to return the same data as in the specified array A without any repetitions.
Syntax: unique(A)
Example:
Matlab
A = [1 2 3 4 5]
B = unique(A)
if length(A)==length(B)
fprintf( 'Each elements are unique.' )
else
fprintf( 'Elements are repeated.' )
end
|
Output:
A =
1 2 3 4 5
B =
1 2 3 4 5
Each elements are unique.
Using Length()
The length() function is used to return the length of the specified array.
Syntax: length(X)
Example:
Matlab
A = [1 2 3 2 4 3 5 5]
B = unique(A)
if length(A)==length(B)
fprintf( 'Each elements are unique.' )
else
fprintf( 'Elements are repeated.' )
end
|
Output:
A =
1 2 3 2 4 3 5 5
B =
1 2 3 4 5
Elements are repeated.
Using Setdiff()
The setdiff() function is used to return the set difference between the two given arrays i.e. the data present in array A but not in B, without any data repetitions.
Syntax: setdiff(A, B)
Example:
Matlab
A = [1 2 3 4 3]
[B] = unique(A)
duplicate_indices = setdiff(1:numel(A), B)
|
Output:
A =
1 2 3 4 3
B =
1 2 3 4
duplicate_indices = 5
Using numel()
The numel() function is used to return the number of elements present in a specified array.
Syntax: numel(A)
Example:
Matlab
A = [0 2 4 1 2 3 0 4]
[B] = unique(A)
duplicate_indices = setdiff(1:numel(A), B)
|
Output:
A =
0 2 4 1 2 3 0 4
B =
0 1 2 3 4
duplicate_indices =
5 6 7 8
Share your thoughts in the comments
Please Login to comment...