How to resolve indexing the sliced variable error in the case of for nested with parfor?

29 次查看(过去 30 天)
I have following use case:
Nth = 102;
p = 0.0000001:0.1:0.99999;
NthArray = (Nth - 100 > 0)*Nth + (Nth - 100 <=0)*1:1:Nth+100;
III = zeros( length(p), length(NthArray));
parfor ip = 1:numel(p)
for inth = 1:numel(NthArray)
III(ip, inth) = g( p(ip), ntharray(inth));
end
end
However, upon running it I get following error:
Error: When indexing the sliced variable 'III', the range of the for-loop variable 'inth' 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".
How should I resolve this error?
Thanks.

回答(1 个)

Edric Ellis
Edric Ellis 2021-4-30
The problem here is that the inner loop bounds must be a constant - basically this means that you must compute it outside the parfor loop, like so:
Nth = 102;
p = 0.0000001:0.1:0.99999;
NthArray = (Nth - 100 > 0)*Nth + (Nth - 100 <=0)*1:1:Nth+100;
III = zeros( length(p), length(NthArray));
% Must calculate inner loop bounds outside the PARFOR loop:
n_Nth = numel(NthArray);
g = @plus; % Dummy definition of "g"
parfor ip = 1:numel(p)
for inth = 1:n_Nth
III(ip, inth) = g( p(ip), NthArray(inth));
end
end
disp('Success!')
Success!
  6 个评论
Edric Ellis
Edric Ellis 2023-11-10
Here's an executable version of my previous comment. Hopefully this includes the salient points from your code, and this does work.
limit = 2*3;
out = zeros(limit, limit, 2);
parfor i = 1:limit
for j = 1:limit
out(i,j,:) = [i j];
end
end
Starting parallel pool (parpool) using the 'Processes' profile ... Parallel pool using the 'Processes' profile is shutting down.
disp(out)
(:,:,1) = 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 6 (:,:,2) = 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by