How do you organize data from a parfor loop?
Mostrar comentarios más antiguos
I'm looking to run a script that has nested for loops in it using parallel processes to speed things up. I need the data to be organized by the indexes. I've been using a 3D array to do this with normal for loops. Im curious if theres a way to get the same results using parfor loops (or any parallel computing alternative).
My code looks something like this, but I want a way to do this same thing using parfor (or something similar):
nlower = 2;
nupper = 4;
tlower = 3;
tupper = 7;
iterations = 6;
%rows are the results for each iteration
%columns are for each size of t
%layers are for each size of n
someVariable = zeros(iterations, (tupper - tlower + 1), (nupper - nlower + 1));
for n = nlower:nupper
for t = tlower:tupper
for iter = 1:iterations
someVariable(iter, (t-tlower + 1), (n - nlower + 1)) = myFunction(iter, t, n);
end
end
end
someVariable %displays the variable to verify results
function value = myFunction(iter, t, n)
value = iter+t+n;
end
Respuesta aceptada
Más respuestas (1)
Edric Ellis
el 30 de Mayo de 2023
You can do this more directly by flattening the parfor loop, and using a combination of ind2sub and reshape. The idea is as follows:
- Instead of a triple-loop, run a single loop over a "linear index"
- Use ind2sub to map back from the "linear index" to co-ordinates
- Use reshape to undo "linear index" piece
Like this:
% dims is the list of sizes in each of 3 dimensions
dims = [iterations, tupper - tlower + 1, nupper - nlower + 1];
parfor idx = 1:(prod(dims))
% idx is the linear index - map this back to co-ordinates back
% in the original dimensions
[xi, xt, xn] = ind2sub(dims, idx);
% Store the result by linear index
out(idx) = myFunction(xi, xt + tlower - 1, xn + nlower - 1);
end
% reshape gets the output matrix back to the right size
someVariable2 = reshape(out, dims);
% Check we got the right answer
assert(isequal(someVariable, someVariable2))
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!