Sliced Variables in N Choose K Search

조회 수: 4(최근 30일)
Andres Morales
Andres Morales 2022년 11월 15일
댓글: Bruno Luong 2022년 11월 16일
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
Bruno Luong
Bruno Luong 2022년 11월 16일
IMO the if test cost is negligible.

댓글을 달려면 로그인하십시오.

채택된 답변

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개)

범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by