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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by