首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >parfor不考虑它中使用的向量的信息

parfor不考虑它中使用的向量的信息
EN

Stack Overflow用户
提问于 2017-06-04 08:28:04
回答 1查看 85关注 0票数 1

这是我在Matlab中代码的一部分。我试图使其并行,但有一个错误:

代码语言:javascript
复制
 The variable gax in a parfor cannot be classified.

我知道错误发生的原因。因为我应该告诉Matlab,v是一个不包含重复元素的增量向量。有人能帮我使用这些信息来并行代码吗?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-04 16:25:53

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

但是,我知道您试图简化这个问题,只是为了了解如何对变量进行切片,所以这里是一个固定版本,可以在parfor中运行。但这肯定不是编写这段代码的方法:

代码语言:javascript
复制
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

向量化的实现如下所示:

代码语言:javascript
复制
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循环比单个循环慢得多,因此在某些情况下(取决于输出的大小),这可能是最快的解决方案:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44352171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档