user729506
user729506

Reputation: 3

Vectorizing for loops

In MATLAB, vectorized code is faster than using for-loops. I have been trying to do this but I do not fully understand how this works. I was hoping someone could show me how to improve these 2 for loops and a while loop with changing indices so I could get my head round it. Any help would be a amazing.

width= 700;
height= 600;
fg= zeros(height, width);
for i= 1: height
    for j= 1: width
        fg(i, j) = 0;
        while ((match== 0)&& (k<= M))
            if (w(i, j, rank_ind(k))>= thresh)
                if (abs(u_diff(i, j, rank_ind(k)))<= D* sd(i, j, rank_ind(k)))
                    fg(i, j)= 0;
                    match= 1;
                else
                    fg(i, j)= fr_bw(i, j); 
                end
            end
            k= k+ 1;
        end
    end
end

Note w, u_diff, sd, rank_ind and fr_b are all arrays

Upvotes: 0

Views: 590

Answers (1)

Jonas
Jonas

Reputation: 74930

Let me see whether I understand you correctly: You want to copy the value of fr_bw into fg only if no corresponding value in u_diff is smaller than D*sd, and w is above some threshold, right?

In this case, you can rewrite your code the following way:

%# find where u_diff is larger than D*sd
%# but not where there's any u_diff that is smaller than D*sd
whereToCopy = any( w(:,:,rank_ind) >= thresh  & ...
  abs(u_diff(:,:,rank_ind)) > D*sd(:,:,rank_ind),3) & ...
  ~any( w(:,:,rank_ind) >= thresh  & ...
  abs(u_diff(:,:,rank_ind)) <= D*sd(:,:,rank_ind),3);

%# whereToCopy has 1 wherever we need to copy, and 0 elsewhere
%# thus, create fg from fr_bw directly by multiplication
fg = double(fr_bw) .* double(whereToCopy);

Upvotes: 1

Related Questions