Azzera filtri
Azzera filtri

How to optimize for loop

2 visualizzazioni (ultimi 30 giorni)
sajeesh c
sajeesh c il 13 Ott 2016
Commentato: Adam il 13 Ott 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 Commento
Adam
Adam il 13 Ott 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.

Accedi per commentare.

Risposte (1)

Jos (10584)
Jos (10584) il 13 Ott 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 :)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by