Testing whether values are unique

91 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2018-2-21
编辑:Stephen23 2018-2-21
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by