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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by