Testing whether values are unique

138 views (last 30 days)
Jonathan Bird
Jonathan Bird on 20 Feb 2018
Edited: Stephen23 on 21 Feb 2018
The user is asked to assign values to sixth variables (a,b,c,d,e,f). I want an errordlg to display in the event any 2 or more variables are given the same value. Preferably, this would be able to say which of the values are not unique. For the first two this is very simple I just did
If b==a
errordlg('the second value is the same as the first');
end
But I'm not sure how to expand this to all sixth variables? Many thanks

Accepted Answer

Stephen23
Stephen23 on 21 Feb 2018
Edited: Stephen23 on 21 Feb 2018
MATLAB works best when data is kept together as much as possible, not split into lots of separate variables. The solution is easier once you put those values into one vector (even better would be to not have separate variables in the first place):
V = [a,b,c,d,e,f];
Then you can simply test to see if any values are repeated:
if numel(V)~=numel(unique(V))
disp('oh no, we have duplicates!')
end
You can easily show which value/s are repeated by getting the index output from unique and processing that:
>> V = [99,10,50,10,0,-1,50];
>> [U,idx,idy] = unique(V,'first');
>> cnt = histc(V,U);
>> U(cnt>1) % duplicate values
ans =
10 50
>> ismember(idy,find(cnt>1)) % locations of duplicates
ans =
0 1 1 1 0 0 1

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!