Effacer les filtres
Effacer les filtres

Testing whether values are unique

97 vues (au cours des 30 derniers jours)
Jonathan Bird
Jonathan Bird le 20 Fév 2018
Modifié(e) : Stephen23 le 21 Fév 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

Réponse acceptée

Stephen23
Stephen23 le 21 Fév 2018
Modifié(e) : Stephen23 le 21 Fév 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
  1 commentaire
Jonathan Bird
Jonathan Bird le 21 Fév 2018
Thanks for this, very helpful!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by