How to execute for-loop iterations in parallel

4 visualizaciones (últimos 30 días)
Vinit Nagda
Vinit Nagda el 2 de Feb. de 2022
Comentada: Ive J el 2 de Feb. de 2022
I want to implement parfor to speed up the calculation but I am facing errors.
How can I implement parfor for the following for loop:
I have a 3D matrix X (DIM: mxnxp)
trues=find(X);
for i=1:size(trues,1)
[x,y,z]=ind2sub([m n p],trues(i,1))
if (condition true)
X(x,y,z)=0;
end
end
Is there any other way I can speed up and optimize execution?
Thank you.
  2 comentarios
Benjamin Thompson
Benjamin Thompson el 2 de Feb. de 2022
Can you post a working example of sequential MATLAB code that implements your algorithm? You can always set all of X to zeros before the for loop to simplify part of your algorithm. parfor usually cannot write to different locations in a matrix in parallel. You may be able to write the result to an output vector in parfor, then redim the output vector to mxnxp.
Vinit Nagda
Vinit Nagda el 2 de Feb. de 2022
m=300;n=300;p=50;
X=ones(m,n,p);
trues=find(X);
for i=1:size(trues,1)
[x,y,z]=ind2sub([m n p],trues(i,1));
if (x>y+z)
X(x,y,z)=0;
end
end
@Benjamin Thompson Here is the working example. Although the if condition is different in real problem, but algorithm remains same.

Iniciar sesión para comentar.

Respuestas (1)

Ive J
Ive J el 2 de Feb. de 2022
Editada: Ive J el 2 de Feb. de 2022
You don't need even a loop (parfor aside) for this (and I guess you don't even need ind2sub depending on your true purpose here):
m=300; n=300; p=50;
X = ones(m, n, p);
trues = find(X > 0);
[x, y, z] = ind2sub([m n p], trues);
idx = x > y + z;
X(trues(idx)) = 0;
  2 comentarios
Vinit Nagda
Vinit Nagda el 2 de Feb. de 2022
@Ive J Thank you for your response. Apparently, in the real problem the if condition check is bit complex rather than simple x > y + z; and therefore requires a loop.
Ive J
Ive J el 2 de Feb. de 2022
Maybe you can explain the probelm itself then :)

Iniciar sesión para comentar.

Categorías

Más información sobre Parallel for-Loops (parfor) en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by