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
% MATLAB code for detection of duplicate
% values of the array using unique()
% Initializing an array A
A = [1 2 3 4 5]
% Calling the unique() function over
% the above array A to return the
% unique values
B = unique(A)
% Using length() function to return
% the size of the above arrays
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
% MATLAB code for detection of duplicate
% values of the array using length()
% Initializing an array A
A = [1 2 3 2 4 3 5 5]
% Calling the unique() function over
% the above array A to return the
% unique values
B = unique(A)
% Using length() function to return
% the size of the above arrays
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
% MATLAB code for detection of duplicate
% values of the array using setdiff()
% Initializing an array
A = [1 2 3 4 3]
% Calling the unique() function
% over the above array to return
% unique elements
[B] = unique(A)
% Using setdiff() and numel() functions
% together to get the indices of repeated
% elements
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
% MATLAB code for detection of duplicate
% values of the array using numel()
% Initializing an array
A = [0 2 4 1 2 3 0 4]
% Calling the unique() function
% over the above array to return
% unique elements
[B] = unique(A)
% Using setdiff() and numel() functions
% together to get the indices of repeated
% elements
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
Explore
Software Engineering Basics
Software Measurement & Metrices
Software Development Models & Agile Methods
SRS & SPM
Testing & Debugging
Verification & Validation
Practice Questions