how to check if there are any elements are equal in a vector

조회 수: 54 (최근 30일)
xueqi
xueqi 2013년 6월 10일
Dear fellows,
Do you know how to write a code to check if are there any (Given that I don't know the numbers)elements are equal in a vector? And then read the element.
Many thanks, Xueqi
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2013년 6월 10일
Please, make it simple, provide a short example, and tell what should be the result

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2013년 6월 10일
The question is still not clear. Perhaps you want:
nonZero = x(x ~= 0);
anyDuplicates = length(unique(nonZero)) ~= length(nonZero);
Or equivalently:
anyDuplicates = ~all(diff(sort(x(x ~= 0))));

추가 답변 (2개)

Daniel Shub
Daniel Shub 2013년 6월 10일
There is no built in function that will do that. You could test the number of unique elements in the vector against the length of the vector
f = @(x)isequal(length(x), length(unique(x)))
I am not sure what you mean by read the element, especially if more than one element is duplicated. Maybe something like
y = 1:length(x);
y(sort(b)) = [];
x(y)
  댓글 수: 3
Daniel Shub
Daniel Shub 2013년 6월 10일
You are missing an end. What is c? What is i?
"But it doesn't seem to work." isn't helpful. What do you want to happen? What happens? Your logic about single duplicates and zero, doesn't make any sense to me. You need to explain it in both words and code.
xueqi
xueqi 2013년 6월 10일
c is a dynamic vector, the element of c(i) is decided by previous elments c(i-1). For example
if true
% 0
0.231095363111135
0
0
0.400000000000000
0
0
0
0.400000000000000
0
0.400000000000000
0.857374060834467
0.0314599355591159
0
0
0
0
0
0
0.446800862782801
end
See in this vector, c(10) should be equal to 0.4 since 0.4 has been shown up for twice previously. But it is still 0...

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2013년 6월 10일
Are they integers, or at least doubles or singles with perfectly, exactly integer values? Do whos() or class() to find out. If they're not integers, you'll have to see if they're within some small tolerance. See the FAQ : http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F for discussion and code example.
  댓글 수: 1
xueqi
xueqi 2013년 6월 10일
Hi, they are not integers. The elments comes from a simulation from the uniform distribution. The point is if there is any two are equal(if are not 0) then it must has be the same pre-speficied value which is 0.4.

댓글을 달려면 로그인하십시오.

카테고리

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