如何避免在 matlab 中嵌套 for 循环?

How to avoid nested for loops in matlab?

我正在根据图像中像素的强度差异构建邻接表。 Matlab中的代码片段如下:

m=1;
len = size(cur_label, 1);
for j=1:len
    for k=1:len
        if(k~=j)    % avoiding diagonal elements
            intensity_diff = abs(indx_intensity(j)-indx_intensity(k));     %intensity defference of two pixels.

            if intensity_diff<=10     % difference thresholded by 10
                adj_list(m, 1) = j;   % storing the vertices of the edge
                adj_list(m, 2) = k;
                m = m+1;
            end
        end
    end
end
y = sparse(adj_list(:,1),adj_list(:,2),1);       % creating a sparse matrix from the adjacency list

如何避免这些讨厌的嵌套 for 循环?如果图像尺寸很大,那么它的工作就像灾难一样。如果有人有任何解决方案,那对我来说将是一个很大的帮助。 问候 拉特那

我在这里假设输入 indx_intensity 作为一个 1D 数组。有了这个假设,这里有一个 broadcasting/bsxfun -

的矢量化方法
%// Threshold parameter
thresh = 10;

%// Get elementwise differentiation between elements in indx_intensity
diffs = abs(bsxfun(@minus,indx_intensity(:),indx_intensity(:).')) %//'

%// Threshold the differentiations against the threshold, thus giving us a 
%// 2D square matrix. Then, set the diagonal elements to zero to avoid them.
mask = diffs <= thresh;
mask(1:len+1:end) = 0;

%// Get the indices of the TRUE elements in the valid mask as final output.
[R,C] = find(mask);
adj_list_out = [C R];