Sliced Variables in N Choose K Search

1 次查看(过去 30 天)
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 个评论
Andres Morales
Andres Morales 2022-11-15
"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.

请先登录,再进行评论。

采纳的回答

Edric Ellis
Edric Ellis 2022-11-16
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by