speed up the for and if loop

7 次查看(过去 30 天)
Lavanya Ashokkumar
Lavanya Ashokkumar 2022-9-15
编辑: VBBV 2022-9-17
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.

回答(1 个)

VBBV
VBBV 2022-9-15
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 个评论
Lavanya Ashokkumar
Lavanya Ashokkumar 2022-9-16
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 2022-9-17
编辑:VBBV 2022-9-17
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

请先登录,再进行评论。

类别

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