I'm trying to write a user-defined function which should determine whether there are any duplicate values in an array.
조회 수: 1 (최근 30일)
이전 댓글 표시
I'm trying to write a user-defined function. This function should determine if an array contains any values which occur more than once, and change the variable bmatch to 1 for true or 0 for false.
At the moment, I'm just trying to work out the algorithm of the function; the script will sometimes work and sometimes not, e.g., when I create an array [4 5 3 4 6 7 8] it won't detect the duplicate, but when the array is [4 5 3 4] it does detect the duplicate.
%data = [4 5 3 4 6 7 8];
for b = 1:length(data)
if sum(data(b) == data) > 1
bmatch = 1;
else
bmatch = 0;
end
end
Please let me know what I'm doing wrong, and if you have a solution to the issue.
댓글 수: 1
VBBV
2023년 4월 22일
편집: VBBV
2023년 4월 25일
May be you need this change in your code
data = [4 5 3 4 6 7 8 10 2 10 2 20 21 7];
for b = 1:length(data)
% this change
if sum(data(b)-data == 0) > 1
% uncomment the below line to show if there is a duplicate value
bmatch = 1;
fprintf('bmatch = %d Num %d\n',bmatch,data(b))
else
bmatch = 0;
end
end
채택된 답변
Sai Kiran
2023년 4월 25일
Hi,
As per my understanding you want a user defined function which returns 1 if any value in the array gets repeated or else 0.
Your code detects the duplicate values but the variable 'bmatch' will only gives the case for the last value in the array. Adding a 'break' keyword whenever you detect a duplicate value ensures you to go out of the loop and give the correct answer.
Here is the modified code for the same.
for b = 1:length(data)
if sum(data(b) == data) > 1
bmatch = 1;
break;
else
bmatch = 0;
end
end
I hope it helps!
Thanks.
댓글 수: 3
Stephen23
2023년 4월 25일
Note that you do not need to loop over all elements, nor is it required to compare against all elements on every iteration. If speed is important then consider other approaches e.g.:
checkdata1([4,5,3,4,6,7,8])
checkdata1([4,5,3,4])
checkdata2([4,5,3,4])
V = 1:1e5;
tic
checkdata0(V)
toc
tic
checkdata1(V)
toc
tic
checkdata2(V)
toc
function bmatch = checkdata0(data) % your function
bmatch = false;
for b = 1:length(data)
if sum(data(b)-data == 0) > 1
bmatch = true;
break
end
end
end
function bmatch = checkdata1(data) % only check remaining elements
bmatch = false;
for k = 2:numel(data)
if nnz(data(k-1)==data(k:end))
bmatch = true;
break
end
end
end
function bmatch = checkdata2(data)
bmatch = ~all(diff(sort(data)));
end
VBBV
2023년 4월 25일
편집: VBBV
2023년 4월 25일
@Jonah @Sai Kiran, One problem with using break inside a loop, is it exits the loop once a duplicate value of a number is found in vector and doesn't check if there are more than one duplicate numbers present in vector.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!