如何在不重复的情况下将数组中的每个元素与其他每个元素进行比较?

How to compare every elements in an array with every other element without repetition?

我想按如下方式处理数据。

例如。 假设数据 x(i)=[1 2 3 5 2 1]。 比较应该是元素 INDEX [1 to 2, 1 to 3, 1 to 4, 1 to 5, 1 to 6, 2 to 3,2 to 4,2 to 5,2 to 6,3 到 4....] 按照上面的逻辑 因此 distance = [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 1, 2, 1] 的元素值。

因此元素值 差异 = [1, 2, 4, 1, 0, 1, 3, 0, 1, 2, 1, 2, 3, 4, 1]. 我为此编写了以下代码,但我注意到我想要的最终矩阵 'b' 总是在改变大小,而它应该是常数。我欢迎任何建议

clc;
close all;
clear all;
% read data set
I= imread('img2.bmp');
G=double(rgb2gray(I));

%choose 2 random numbers
n = 1; 
s = [1 960];
k = round(rand(n,1)*range(s)+min(s));

for i = 1:length(k)
% choose a particular row from a matrix
row_no=k(i);
%G=R(row_no,:);

% compare every element with its neigbour to create distance and difference     matrix 
x1=row_no;
x2=row_no;

        for y1 = 1:length(G)%size(G,2)
                for y2 =1:length(G) %1:size(G,2)
                    distance_Mat(y1,y2) = round(sqrt((y2-y1)^2 + (x2-x1)^2));
                    difference_Mat(y1,y2) = 1*(G(x1,y1) - G(x2,y2))^2;
                end
        end

%% now remove repeating comparisons             
b=horzcat(distance_Mat(:),(difference_Mat(:)));
[UniXY,Index]=unique(b,'rows');
DupIndex=setdiff(1:size(b,1),Index);
b(DupIndex,:)=[];
%calculate the cumulative sums and store it in different colums of data matrix
A1 = cumsum(b);
data(:,1)=A1;
end

如果您有统计工具箱,那么

distance_Mat = squareform(pdist(x'));

每次只比较一次,然后镜像数据。您可以通过

获得下半部分
tril(distance_Mat,-1);

如果您没有工具箱,请试试这个:

I = tril(ones(numel(x)),-1);
[r,c] = find(I);

distance_Mat = zeros(numel(x)); 
distance_Mat(logical(I)) = round(sqrt((x(r)-x(c)).^2)