how to detect repeated values in an array in matlab

To detect repeated values in an array in MATLAB, you can use the unique function along with the diff function:

main.m
arr = [1, 2, 3, 2, 4, 5, 3, 5, 6, 7];
[uniqueArr, ~, idx] = unique(arr);
repeatedIdx = find(diff(idx) == 0);
repeatedVals = uniqueArr(idx(repeatedIdx));
153 chars
5 lines

In the above code, we first use unique function to get unique values from array arr, and then use diff function on the index of unique array to find out the repeated values. find function is used to get the index of repeated values in the original array. Finally, repeated_vals contains the repeated values.

Alternatively, if you want to know if any element is repeated in an array, you can use length(unique(arr)) ~= length(arr) as a condition. This will return true if there are repeated elements in the array.

related categories

gistlibby LogSnag