Can someone help vectorize this loop?

13 Ansichten (letzte 30 Tage)
DEVANAND
DEVANAND am 28 Jul. 2015
Bearbeitet: Matt J am 28 Jul. 2015
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

Antworten (1)

Matt J
Matt J am 28 Jul. 2015
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 Kommentar
Matt J
Matt J am 28 Jul. 2015
Bearbeitet: Matt J am 28 Jul. 2015
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by