parfor 不考虑有关其中使用的向量的信息

parfor doesn't consider information about vectors which are used in it

这是我在 Matlab 中的代码的一部分。我试图让它平行,但出现错误:

 The variable gax in a parfor cannot be classified.

我知道为什么会出现这个错误。因为我应该告诉 Matlab v 是一个不包含重复元素的递增向量。谁能帮我使用这些信息来并行化代码?

v=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
for m=v
if m > 1 
    parfor j=1:m-1
        gax(j,m-1) = ggx(j,m-1); 
    end
end
if m<nn 
    parfor jo=m+1:15 
        gax(jo,m) = ggx(jo,m); 
    end
end
end

优化代码应该与其目的密切相关,尤其是当您使用 parfor 时。您在问题中编写的代码可以以更有效的方式编写,并且绝对不需要并行化。

但是,我了解到您试图简化问题,只是为了了解如何对变量进行切片,所以这里是 can [=26] 的固定版本=] 与 parfor。但这肯定不是写这段代码的方式:

v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;
for m = v
    if m > 1
        temp_end = m-1;
        temp = ggx(:,temp_end);
        parfor ja = 1:temp_end
            gax(ja,temp_end) = temp(ja);
        end
    end
    if m < nn
        temp = ggx(:,m);
        parfor jo = m+1:15
            gax(jo,m) = temp(jo);
        end
    end
end

矢量化实现如下所示:

v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;

m1 = v>1; % first condition with logical indexing
temp = v(m1)-1; % get the values from v
r = ones(1,sum(temp)); % generate a vector of indicies
r(cumsum(temp)) = -temp+1; % place the reseting locations
r = cumsum(r); % calculate the indecies
r(cumsum(temp)) = temp; % place the ending points
c = repelem(temp,temp); % create an indecies vector for the columns
inds1 = sub2ind(size(gax),r,c); % convert the indecies to linear

mnn = v<nn; % second condition with logical indexing
temp = v(mnn)+1; % get the values from v
r_max = size(gax,1); % get the height of gax
r_count = r_max-temp+1; % calculate no. of rows per value in v
r = ones(1,sum(r_count)); % generate a vector of indicies
r([1 r_count(1:end-1)+1]) = temp; % set the t indicies
r(cumsum(r_count)+1) = -(r_count-temp)+1; % place the reseting locations
r = cumsum(r(1:end-1)); % calculate the indecies
c = repelem(temp-1,r_count); % create an indecies vector for the columns
inds2 = sub2ind(size(gax),r,c); % convert the indecies to linear

gax([inds1 inds2]) = ggx([inds1 inds2]); % assgin the relevant values

这确实很复杂,并不总是必要的。不过要记住的一点是,嵌套 for 循环比单个循环慢得多,因此在某些情况下(取决于输出的大小),这可能是最快的解决方案:

for m = v
    if m > 1
        gax(1:m-1,m-1) = ggx(1:m-1,m-1);
    end
    if m<nn
        gax(m+1:15,m) = ggx(m+1:15,m);
    end
end