フィルターのクリア

Can someone help vectorize this loop?

1 回表示 (過去 30 日間)
DEVANAND
DEVANAND 2015 年 7 月 28 日
編集済み: Matt J 2015 年 7 月 28 日
Hi, Can this code be vectorized. If so, can someone help me to do so. Thanks in advance. C is a 201*201 2D matrix.
for l=2:N-1
for m= 2:N-1
rd=randi([0 8]);
if rd ==0
C(l,m)=C(l,m) - 1;
C(l,m+1)=C(l,m+1)+1;
elseif rd ==1
C(l,m)=C(l,m) - 1;
C(l+1,m+1)=C(l+1,m+1)+1;
elseif rd ==2
C(l,m)=C(l,m) - 1;
C(l+1,m)=C(l+1,m)+1;
elseif rd ==3
C(l,m)=C(l,m) - 1;
C(l+1,m-1)=C(l+1,m-1)+1;
elseif rd ==4
C(l,m)=C(l,m) - 1;
C(l,m-1)=C(l,m-1)+1;
elseif rd ==5
C(l,m)=C(l,m) - 1;
C(l-1,m-1)=C(l-1,m-1)+1;
elseif rd ==6
C(l,m)=C(l,m) - 1;
C(l-1,m)=C(l-1,m)+1;
elseif rd ==7
C(l,m)=C(l,m) - 1;
C(l-1,m+1)=C(l-1,m+1)+1;
elseif rd ==8
C(l,m)=C(l,m);
end
end
end

回答 (1 件)

Matt J
Matt J 2015 年 7 月 28 日
reorder=[8 9 6 3 2 1 4 7 5];
[X,Y]=ndgrid(1:3);
Increm = sub2ind(size(C),X,Y)-sub2ind(size(C),2,2);
Increm(5)=0;
Increm=Increm(reorder);
Lookup=randi([1,9],size(C)-2);
Lidx=reshape(1:numel(C),size(C));
Lidx([1,end],:)=[];
Lidx(:,[1,end])=[];
Linc= Increm(Lookup);
LidxInc=Lidx+Linc;
subs=[Lidx(:),LidxInc(:)];
v=logical(Linc(:));
val=[-v,v];
Delta=accumarray(subs(:),val(:),[numel(C),1]);
C=C+reshape(Delta,size(C));
  1 件のコメント
Matt J
Matt J 2015 年 7 月 28 日
編集済み: Matt J 2015 年 7 月 28 日
For comparison, you can verify that the above produces the same result as this slightly rewritten, but equivalent version of your code:
N=length(C);
Rd=Lookup.'-1; %<-----modified
cc=0;
for l=2:N-1
for m= 2:N-1
cc=cc+1;
rd=Rd(cc); %<-----modified
if rd ==0
C(l,m)=C(l,m) - 1;
C(l,m+1)=C(l,m+1)+1;
elseif rd ==1
C(l,m)=C(l,m) - 1;
C(l+1,m+1)=C(l+1,m+1)+1;
elseif rd ==2
C(l,m)=C(l,m) - 1;
C(l+1,m)=C(l+1,m)+1;
elseif rd ==3
C(l,m)=C(l,m) - 1;
C(l+1,m-1)=C(l+1,m-1)+1;
elseif rd ==4
C(l,m)=C(l,m) - 1;
C(l,m-1)=C(l,m-1)+1;
elseif rd ==5
C(l,m)=C(l,m) - 1;
C(l-1,m-1)=C(l-1,m-1)+1;
elseif rd ==6
C(l,m)=C(l,m) - 1;
C(l-1,m)=C(l-1,m)+1;
elseif rd ==7
C(l,m)=C(l,m) - 1;
C(l-1,m+1)=C(l-1,m+1)+1;
elseif rd ==8
C(l,m)=C(l,m);
end
end
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by