How to optimize for loop

1 次查看(过去 30 天)
sajeesh c
sajeesh c 2016-10-13
评论: Adam 2016-10-13
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 个评论
Adam
Adam 2016-10-13
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.

请先登录,再进行评论。

回答(1 个)

Jos (10584)
Jos (10584) 2016-10-13
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 :)

类别

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