speed up the for and if loop

7 visualizaciones (últimos 30 días)
Lavanya Ashokkumar
Lavanya Ashokkumar el 15 de Sept. de 2022
Editada: VBBV el 17 de Sept. de 2022
Hi,
I have a for and if loop that takes several hours to run. I tried to vectorize the for loop, but the main issue is the way I use the if statement in my script. Refering the array values at subscript is really important, because if i don't use the subscript the final values (melt) are incorrect. Is there way to speed-up my processing time, while taking care of the subscripts in a three dimensional array.
for i = 1:300
for j = 1:500
for k = 1:17000
if(temp(i,:) > 2)
melt(i,j,k) = temp(i,j,k) .* 3;
else
melt(i,j,k) = 0;
end
end
end
end
Thank you.

Respuestas (1)

VBBV
VBBV el 15 de Sept. de 2022
for i = 1:10:300 % use step increments
for j = 1:10:500
for k = 1:1000:17000
if(temp(i,:) > 2)
melt(i,j,k) = temp(i,j,k) .* 3;
else
melt(i,j,k) = 0;
end
end
end
end
  3 comentarios
Lavanya Ashokkumar
Lavanya Ashokkumar el 16 de Sept. de 2022
Thanks for the reply. If I use increments in for loop, the skipped portions of the loop end up having zero values. Ultimately, this affects the final values of melt.
VBBV
VBBV el 17 de Sept. de 2022
Editada: VBBV el 17 de Sept. de 2022
I = 1:10:300;
J = 1:10:500
K = 1:1000:17000
for i = 1:length(I) % use step increments
for j = 1:length(J)
for k = 1:length(K)
if(temp(I(i),:) > 2)
melt(I(i),J(j),K(k)) = temp(I(i),J(j),K(k)) .* 3;
else
melt(I(i),J(j),K(k)) = 0;
end
end
end
end
An alternative way to avoid problem of zeros values in matrix can be done using above
% or use
melt(melt == 0) = []; % to get rid of zeros in the final matrix

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements 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