MATLAB: How to find duplicate values in a structure

MATLAB

I would like to find all the fields and values from a structure having duplicate values.

Best Answer

Find below the function that takes structure "s" as input and gives you a cell array with duplicates. Please note that output of the below function would be a cell array. If you need a structure instead of cell array as output, please return the "newStruct" value in the below function.
function finalDuplicatesCellArray = selectDuplicates(s)
keys = fieldnames(s);
values = struct2array(s);
uniqueValues = unique(values);
valueCounts = histcounts(values, length(unique(values)));
idx = valueCounts > 1;
duplicatedValues = uniqueValues(idx);
duplicateValuesIndices = ismember(values,duplicatedValues, 'legacy');
duplicateKeys = keys(duplicateValuesIndices);
duplicateValues = values(duplicateValuesIndices);
newStruct = struct;
for ii = 1:length(duplicateKeys)
newStruct.(char(duplicateKeys(ii))) = duplicateValues(ii);
end
%Convert the newStruct to cell array
valuesFinal = num2cell(duplicateValues');
finalDuplicatesCellArray = [duplicateKeys,valuesFinal];
end
Input example: S.A = 1; S.C = 1; S.E = 1; S.F = 1;
Output: 4×2 cell array
'A' [1]
'C' [1]
'E' [1]
'F' [1]