Speeding up IF-FOR loop

4 views (last 30 days)
Mohsen
Mohsen on 19 Jun 2013
How can I optimize this code so that it runs faster:
iNZ=11; iNCUr=55;
UrPointX=zeros(iNCUr);
UrPointY=zeros(iNCUr); UrContourZ=[ 0 0 0 0 0 -5 -5 -5 -5 -5 -10 -10 -10 -10 -10 -10 -15 -15 -15 -15 -15 -15 -20 -20 -20 -20 -20 -20 -25 -25 -25 -25 -30 -30 -30 -30 -30 -30 -35 -35 -35 -35 -35 -35 -40 -40 -40 -40 -40 -40 -45 -45 -45 -45 -45]; ZSlice=[ 5 0 -5 -10 -15 -20 -25 -30 -35 -40 -45];
UrContourX=[ 69.103 70.633 71.05 70.911 68.964 69.938 68.408 69.103 69.938 70.633 67.713 68.686 69.659 70.007 70.285 69.52 67.018 68.269 69.381 69.938 69.103 68.964 69.729 67.713 67.921 68.547 69.868 70.216 70.494 68.408 68.825 70.355 70.633 70.702 70.007 68.964 68.2 68.964 70.911 69.52 69.52 67.991 69.103 70.077 70.077 69.242 68.478 69.173 70.772 70.772 70.633 68.964 69.242 70.633 70.633];
UrContourY=[ 44.801 45.914 47.026 47.026 46.887 50.919 49.946 48.556 48.417 49.112 52.24 50.711 50.641 50.989 51.754 53.144 54.534 52.866 52.866 54.395 55.369 55.369 55.994 55.508 54.187 53.352 53.422 55.508 56.62 56.481 53.839 53.978 54.117 55.438 56.272 56.272 55.786 53.7 54.256 55.925 56.064 55.09 53.561 53.839 53.492 53.422 52.935 51.614 52.24 52.588 51.058 50.78 49.668 50.224 50.919];
Offset=[ 6.8947; -16.648; 5];
for i=1:iNZ;
iPointsinSlice=1;
for j=1:iNCUr;
if UrContourZ(j)==ZSlice(i);
iPointsinSlice = iPointsinSlice+1;
UrPointX(iPointsinSlice-1)=1 + (UrContourX(j)-Offset(1,1));
UrPointY(iPointsinSlice-1)=1 + (UrContourY(j)-Offset(2,1));
end
end
if iPointsinSlice>0;
indx=round(iPointsinSlice);
indy=round(iPointsinSlice);
indx(1:iPointsinSlice-1)=UrPointX(1:iPointsinSlice-1)/DresX;
indy(1:iPointsinSlice-1)=UrPointY(1:iPointsinSlice-1)/DresY;
SliceMaskUr = poly2mask(indx,indy,iNNX,iNNY);
for m=1:iNX;
for l=1:iNY;
if SliceMaskUr(m,l)==1;
DoseCubeU(m,l,i)=100*SumDose(m,l,i)/RX_Dose;
end
end
end
end
end
My goal is to optimize this code and I would highly appreciate your help.
  2 Comments
Andrew Newell
Andrew Newell on 19 Jun 2013
Please provide code that will actually run as shown. At least four variables are not defined: DresX, DresY, iNNX, iNNY.
Mohsen
Mohsen on 19 Jun 2013
DresX=1; DresY=1; iNNX=double(iNX); iNNY=double(iNY):

Sign in to comment.

Answers (3)

Andrew Newell
Andrew Newell on 19 Jun 2013
One thing you could do to speed things up is to pre-allocate DoseCubeU using a command like
DoseCubeU = zeros(iNX,iNY,iNZ);

Jan
Jan on 19 Jun 2013
This pre-allocates a square matrix, but it looks like you want a vector only:
UrPointX=zeros(iNCUr);

Iain
Iain on 19 Jun 2013
You may be able to speed up the operation using elementwise operations, logical addressing, matrices and bsxfun

Products

Community Treasure Hunt

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

Start Hunting!