How to check whether any two elements are equal or not in a Nx1 array in matlab?

23 visualizaciones (últimos 30 días)
Dear all,
I have one column matrix with N array, and I want to check whether any two elements are equal or not? And if two or more numbers are equal, how to find their position on the array? How can I do that by coding?
Thanks

Respuesta aceptada

Guillaume
Guillaume el 19 de Nov. de 2019
x = [1 2 3 4 2 5 6 3 7 8 9 10]; %demo data. Works with column or row vectors
[loc1, loc2] = find(tril(x == x.', -1)); %location of duplicates
dupvalues = x(loc1); %same as x(loc2) obviously
table(dupvalues(:), loc1, loc2, 'VariableNames', {'DuplicateValue', 'FirstIndex', 'SecondIndex'}) %for pretty display

Más respuestas (1)

Vladimir Sovkov
Vladimir Sovkov el 19 de Nov. de 2019
%%
z=randi(5,10,1); % forms a sample array; replace it with an array of your interest
%%
[~,indx]=sort(z);
k0=1;
while k0<=numel(z)
if k0<numel(z)
k1=find(z(indx(k0+1:end))>z(indx(k0)),1); % if you do not need the exact coincidence but a tolerant closeness, change it to "k1=find(z(indx(k0+1:end))-z(indx(k0))>epss,1)" with the epss being the satisfying tolerance
else
k1=[];
end
if isempty(k1)
k1=numel(z);
else
k1=k1+k0-1;
end
disp(strcat('for z=',num2str(z(indx(k0)))));
disp(sort(indx(k0:k1))');
k0=k1+1;
end

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by