I'm trying to write a user-defined function which should determine whether there are any duplicate values in an array.
Show older comments
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 Comment
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
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!