# How to vectorize this code to eliminate nested For loops?

1 visualización (últimos 30 días)
Jae Min Lee el 6 de Sept. de 2018
Comentada: Greg el 6 de Sept. de 2018
Would like to know how this code is vectorized:
for r=1:rows
for c=1:cols
if ((Lin <= Limg(r,c)) && (Limg(r,c) <= Hin))
enhanceImg(r,c) = Lout + (Hout - Lout) * ((Limg(r,c) - Lin) / (Hin - Lin))^gamma;
elseif (Limg(r,c) > Lin)
enhanceImg(r,c) = Hout;
else
enhanceImg(r,c) = Lout;
end
end
end
Lin, Hin, Lout, Hout, gamma are scalar values.
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Greg el 6 de Sept. de 2018
+1 for a very well formed question. Clear and concise, showed an attempt, and described relevant variable sizes.
That all makes it much easier to answer.

Iniciar sesión para comentar.

Greg el 6 de Sept. de 2018
Editada: Greg el 6 de Sept. de 2018
Most of that is straightforward, just a couple elementwise periods for safety. Then, the hardest part is getting the logic to put the right values into your output matrix.
%%%Pre-allocate to Lout saves one round of comparison + assignment
enhancedImg = Lout.*ones(rows,cols);
blnOne = (Lin <= Limg) & (Limg <= Hin);
%%%Assign the arithmetic result to elements behind that mask
enhancedImg(blnOne) = Lout+(Hout-Lout).*((Limg(blnOne)-Lin)./(Hin-Lin)).^gamma;
%%%Another mask for the elseif condition
blnTwo = Limg > Lin;
%%%Assign Hout to those elements
enhancedImg(blnTwo) = Hout;
%%%As mentioned above, all remaining elements are already Lout, so no "else" condition is needed
EDIT: Fixed Limg(blnOne) per first comment below.
##### 4 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Jae Min Lee el 6 de Sept. de 2018
Thank you very much!
Greg el 6 de Sept. de 2018
Happy to help.

Iniciar sesión para comentar.

### Categorías

Más información sobre Programming en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by