Sliced Variables in N Choose K Search

1 visualizzazione (ultimi 30 giorni)
I am trying to generate computations for a problem of the form N Choose K. The function is computational expensive, so I would like to use parallel computing. Using a preallocated array and sliced variables, originally my code looked like this:
A = NaN(100,100);
parfor x = 1:100
for y = x+1:100
A(x,y) = somefunction(x,y)
end
end
When I try to run I get the following error:
Error: When indexing the sliced variable 'A', the range of the for-loop variable 'y' must be a row vector of positive constant numbers or variables. For more information, see Parallel for Loops in MATLAB, "Nested for-Loops with Sliced Variables".
The problem is the y variable as it is not constant. To solve this issue, I changed the code to:
A = NaN(100,100);
parfor x = 1:100
for y = 1:100
if y > x
A(x,y) = somefunction(x,y)
end
end
end
Which it now works. However, it seems to me that having to run the check y > x so many times is very inefficient.
Would there be a better way?
  2 Commenti
Andres Morales
Andres Morales il 15 Nov 2022
"However, it seems to me that having to run the check y > x so many times is very inefficient."
Not sure if the statement above is valid. Maybe doing the y = x+1:100 is more inefficient.
Bruno Luong
Bruno Luong il 16 Nov 2022
IMO the if test cost is negligible.

Accedi per commentare.

Risposta accettata

Edric Ellis
Edric Ellis il 16 Nov 2022
This is a limitation of the parfor analysis when it comes to indexing sliced variables in a nested for loop. There is another workaround, but I suspect it is actually even less efficient than the one that you found:
somefunction = @(x,y) x+y;
A = NaN(10);
parfor x = 1:10
tmp = A(x,:); % Extract row x
for y = (x+1):10
tmp(y) = somefunction(x,y);
end
A(x,:) = tmp;
end
Starting parallel pool (parpool) using the 'Processes' profile ... Connected to the parallel pool (number of workers: 2).
disp(A)
NaN 3 4 5 6 7 8 9 10 11 NaN NaN 5 6 7 8 9 10 11 12 NaN NaN NaN 7 8 9 10 11 12 13 NaN NaN NaN NaN 9 10 11 12 13 14 NaN NaN NaN NaN NaN 11 12 13 14 15 NaN NaN NaN NaN NaN NaN 13 14 15 16 NaN NaN NaN NaN NaN NaN NaN 15 16 17 NaN NaN NaN NaN NaN NaN NaN NaN 17 18 NaN NaN NaN NaN NaN NaN NaN NaN NaN 19 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

Più risposte (0)

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by