How to optimize for loop

2 ビュー (過去 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 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