矢量化循环

时间:2011-04-28 17:00:48

标签: matlab vectorization

在MATLAB中,矢量化代码比使用for循环更快。我一直试图这样做,但我不完全理解这是如何工作的。我希望有人可以告诉我如何改进这2个for循环和一个while循环,改变索引,所以我可以让我的头围绕它。任何帮助都会很棒。

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

注意wu_diffsdrank_indfr_b都是数组

1 个答案:

答案 0 :(得分:1)

让我看看我是否理解正确:您希望仅当fr_bw中的相应值小于fg时才将u_diff的值复制到D*sd,并且w超过某个阈值,对吧?

在这种情况下,您可以通过以下方式重写代码:

%# 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);