I'm trying to write a user-defined function which should determine whether there are any duplicate values in an array.
Afficher commentaires plus anciens
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 commentaire
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
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Elementary Math dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!