Vectorization of For loops

1 次查看(过去 30 天)
Jason Renz Reyes
Jason Renz Reyes 2018-1-26
回答: Eric 2018-2-2
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')
image = imread(FILENAME);
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

回答(1 个)

Eric
Eric 2018-2-2
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,:);

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by