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

8 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2019-11-19
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

更多回答(1 个)

Vladimir Sovkov
Vladimir Sovkov 2019-11-19
%%
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by