问题描述
我有这个(很长的)带有嵌套循环的Matlab代码,在这里我想并行化主要的耗时迭代. (显然)给我带来问题的唯一变量是DMax
,出现错误:
I have this (quite long) Matlab code with nested loops where I want to parallelize the main time-consuming iteration. The only variable that (apparently) gives me problems is DMax
, where I get the error:
Error: The variable DMax in a `parfor` cannot be classified.
See Parallel for Loops in MATLAB, "Overview".
这是我的代码草稿:
t0=matrix (Maxiter,1); % This is a big matrix whose dimensions are reported in brachets
Maxiter = 1E6;
DMax = zeros(Maxiter,40);
% Other Stuff
for j=1:269
% Do more stuff
for soil=1:4
parfor i =1:Maxiter
k(i,soil) = a %k is a real number
a(i,soil) = b %similar to k
% Do a lot of stuff
for t= (floor(t0(i,soil))+1):40
DMax(i,t) = k(i,soil)*((t-t0(i,soil))^a(i,soil));
% Do some more stuff
end
end
end
end
for time=1:40
% Do the final stuff
end
我想问题出在我定义DMax的方式上,但是我不知道它可能更精确.我已经在网上看过了,但结果却不太令人满意.
I guess the problem is in the way I defined DMax, but I do not know what it could be more precisely. I already looked on the web but with not very satisfying results.
推荐答案
文档,必须将parfor中的每个变量分类为几种类型之一.您的DMax
变量应为 sliced变量(其段由循环的不同迭代操作的数组),但为了将其分类为所有以下条件都必须满足:
It is very clearly described in the documentation that each variable inside parfor must be classified into one of several types. Your DMax
variable should be a sliced variable (arrays whose segments are operated on by different iterations of the loop), but in order to be classified as such, all the following conditions must hold:
很显然,固定索引列表属性不成立,因为您将其引用为DMax(i,t)
,其中t会更改其值.文档中有一个相同的示例,请注意.因此,一种解决方法是在内部循环内使用一个临时变量,然后将整个行分配回DMax
.
Clearly, Fixed Index Listing property does not hold since you reference it as DMax(i,t)
where t changes its values. There's an identical example described in the documentation, please pay attention. So one workaround would be to use a temporary variable inside the inner loop, and then assign the whole row back to DMax
.
还请注意,变量a
也不能分类为任何类别.更不用说您的示例中完全没有定义它.请仔细阅读该指南,并确保可以将其分类为以下类别之一.根据需要重写代码,例如引入新的临时变量.
Also note that variable a
cannot be classified into any category either. That's not to mention that it's not defined in your example at all. Please read the guide carefully and make sure it can be classified into one of the categories. Rewrite the code if needed, e.g. introducing new temporary variables.
以下是纠正了DMax
使用情况的代码:
Here's the code where DMax
usage is corrected:
Maxiter = 1E6;
t0 = randn(Maxiter,1); % This is a big matrix whose dimensions are reported in brachets
DMax = zeros(Maxiter,40);
% Other Stuff
for j = 1:269
% Do more stuff
for soil = 1:4
parfor i = 1:Maxiter
k(i,soil) = a %k is a real number
a(i,soil) = b %similar to k
% Do a lot of stuff
tmp = zeros(1,40);
for t = (floor(t0(i,soil))+1):40
tmp(t) = k(i,soil)*((t-t0(i,soil))^a(i,soil));
% Do some more stuff
end
DMax(i,:) = tmp;
end
end
end
for time = 1:40
% Do the final stuff
end
这篇关于Matlab中并行处理期间的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!