フィルターのクリア

Testing whether values are unique

91 ビュー (過去 30 日間)
Jonathan Bird
Jonathan Bird 2018 年 2 月 20 日
編集済み: Stephen23 2018 年 2 月 21 日
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
  1 件のコメント
Jonathan Bird
Jonathan Bird 2018 年 2 月 21 日
Thanks for this, very helpful!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by