필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by