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 CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by