在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
注意w
,u_diff
,sd
,rank_ind
和fr_b
都是数组
答案 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);