speed up the for and if loop
7 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
VBBV
on 15 Sep 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 Comments
VBBV
on 17 Sep 2022
Edited: VBBV
on 17 Sep 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
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!