How to optimize for loop

조회 수: 10 (최근 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