Search code examples
matlabvectorizationadjacency-listadjacency-matrix

How to avoid nested for loops in matlab?


I am constructing an adjacency list based on intensity difference of the pixels in an image. The code snippet in Matlab is as follows:

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

How can I avoid these nasty nested for loops? If the image size is big, then its working just as disaster. If anyone have any solution, it would be a great help for me. Regards Ratna


Solution

  • I am assuming the input indx_intensity as a 1D array here. With that assumption, here's a vectorized approach with 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];