How to avoid nested for loops in matlab?

别说谁变了你拦得住时间么 提交于 2019-12-24 16:52:36

问题


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


回答1:


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];


来源:https://stackoverflow.com/questions/36417710/how-to-avoid-nested-for-loops-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!