# Vectorization of For loops

1 view (last 30 days)
Jason Renz Reyes on 26 Jan 2018
Answered: Eric on 2 Feb 2018
Hi I am trying to get the location of the pixels of an image file using a specific sequence and saving it to a specific location. How could I vectorize my for loops to get a lower run time?
[FILENAME, EXT, USER_CANCELED] = uigetfile('*.jpg')
figure, imshow(FILENAME), title('Original Image')
[im_row,im_col,rgbdim]=size(image);
total_pix=im_row*im_col; %total number of pixels
tf = ceil(0.75*total_pix); %75 percent of the image
pixprow = ceil(tf/im_row);
pix_count=0;
for i=1:im_row
for j=1:pixprow
pix_count=pix_count+1;
rloc1(pix_count,1)=i;
rloc1(pix_count,2)=im_col-j;
end
end
sub=0;
sub2=0;
for
i=1:2:pix_count-1;
sub=sub+1;
rloc(i,:)=rloc1(sub,:);
rloc(i+1,:)=rloc1(pix_count-sub2,:);
sub2=sub2+1;
end

Eric on 2 Feb 2018
Honestly, your slow code is due to the fact that you don't preallocate rloc1 or rloc. You will find that simply adding
rloc1 = zeros(im_row*pixprow,2);
rloc = rloc1;
just before the first loop will already great improve your run time. But to answer your question, you can replace for loop 1 with:
pix_count = im_row*pixprow;
rloc1 = zeros(pix_count,2);
[rloc1(:,2) rloc1(:,1)] = ind2sub([pixprow im_row],1:pix_count);
rloc1(:,2) = im_col - rloc1(:,2);
and loop 2 with:
rloc = zeros(size(rloc1));
rloc(2:2:pix_count,:) = rloc1(pix_count:-1:pix_count/2+1,:);
rloc(1:2:pix_count,:) = rloc1(1:pix_count/2,:);