How to optimize for loop

1 view (last 30 days)
sajeesh c
sajeesh c on 13 Oct 2016
Commented: Adam on 13 Oct 2016
Hi all..i have a 1424x2144 image.i want to process each pixel in the image to find a new pixel value.And i want to create a new 1424x2144 matrix for the new image. I have the following code
if true
for i=1:1424
for j=2:2144
finding new pixel values.
newimg(i,j)=value;
end
end
end
But it takes about 30 seconds to complete the iterations. How to speedup the execution time.?
  1 Comment
Adam
Adam on 13 Oct 2016
Clearly it depends what 'finding new pixel values' does/means.
As it is you seem you be just assigning the same value to every pixel which you can do in 1 line very quickly.

Sign in to comment.

Answers (1)

Jos (10584)
Jos (10584) on 13 Oct 2016
I think I am missing something. Why runs j from 2 instead of 1? Is value a constant? If so, this would suffice:
newimg = repmat(value,1424,2144) ;
newimg(:,1) = 0 ;
In any case, if you use for-loops to create a new matrix, you can speed things up tremendously by pre-allocating the matrix. In your situation:
newimg = zeros(1424,2144) ; % pre-allocation with zeros
for i=1:1424
for j=2:2144
finding new pixel values.
newimg(i,j)=value;
end
end
If you have looked carefully, the matlab editor warns for this. There is a red line under newimg and when you hover over it with your cursor it a message pops up " The variable appears to be growing inside a loop ...".It is gives a suggestion to fix it :)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!