convert for into parfor
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi,
I've read through some parfor information but I am struggling to understand some of the implementation.
At the moment I am using a for loop. For simplicity it looks something like this:
Itterations=1000;
MyVariable=[10,20];
for i=1:length(MyVariable)
X=MyVariable(i);
Table=[];
counter1=0;
counter2=0;
%nested loop with its own nested loop
for j=1:Itterations
MyInt=*random number generator to produce an integer*
counter1=counter1+MyInt;
Table=[Table;zeros(MyInt,5)];
*do some stuff on the items in the table, which is conditional on MyVariable value*
if *condition is met in the table == something*
for all rows that meet the condition (counting down)
Table(k,:)=[] %remove the row
counter2=counter2+number of rows removed;
end
end
end
display counters' value
end
What I would like to do is use multiple cpu cores, each core working on its own Table using MyVariable. Instead of running the inner nested loop twice (in this case), for each MyVariable value, I would like to run two instances of the nested loop. Is this possible? It would be great if there could be two instances of each variable that would not interact (effectively sandbox each instance of the nested loop) but I get the impression that this is not possible so I am trying to understand how I modify my code so I could use parfor. Help would be very much appreciated.
Thank you.
0 comentarios
Respuestas (1)
Kris Fedorenko
el 8 de Sept. de 2017
Hi!
If I understand your question correctly, you would like to parallelize working with each value from MyVariable, i.e. turn your most outer loop (for i=1:length(MyVariable)) into a parfor. I do not see any issues with that, as each iteration of that loop is independent (operates with and changes its own set of variables like Table). For examples of possible issues and fixes for them you can refer to this documentation page: https://www.mathworks.com/help/distcomp/nested-parfor-loops-and-for-loops.html
I would also be careful with your most inner loop (over rows of Table meeting a certain condition). It looks like you are looping over the rows of the Table while also removing rows from the Table. Consider the following example, where we try to remove every other row of A:
A = randn(10, 5);
for k=2:2:10
k
A(k,:) = [];
end
With this for loop we will run into index out of range problem (while also deleting the wrong rows, as the indices would shift as we remove rows). Instead we can accomplish the task like this:
A = randn(10, 5);
k=2:2:10;
A(k,:) = [];
I hope this helps!
Kris
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!