Can someone help vectorize this loop?

13 vues (au cours des 30 derniers jours)
DEVANAND
DEVANAND le 28 Juil 2015
Modifié(e) : Matt J le 28 Juil 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

Réponses (1)

Matt J
Matt J le 28 Juil 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 commentaire
Matt J
Matt J le 28 Juil 2015
Modifié(e) : Matt J le 28 Juil 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by