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

23 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Guillaume
Guillaume am 19 Nov. 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

Weitere Antworten (1)

Vladimir Sovkov
Vladimir Sovkov am 19 Nov. 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

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by