代码之家  ›  专栏  ›  技术社区  ›  sodiumnitrate

parfor中的递增数组?

  •  1
  • sodiumnitrate  · 技术社区  · 5 年前

    我根据3d空间中一对点之间的距离计算直方图:

    numBins = 20;
    binWidth = 2.5;
    pop = zeros(1,numBins);
    parfor j=1:particles
        r1 = coords(j,:);
        for k=j+1:particles
            r2 = coords(k,:);
            d = norm(r1-r2);
            ind = ceil(d/binWidth);
            pop(ind) = pop(ind) + 1;
        end
    end
    

    Error: The variable pop in a parfor cannot be classified.
    

    我理解这个问题,但我不知道怎样才能解决它。 n 副本 pop = zeroes(1,numBins) N 工人,并在计算结束时将每个副本添加到一起。我在这里怎么做?还是有其他更标准的方法来解决这个问题?

    0 回复  |  直到 5 年前
        1
  •  3
  •   obchardon    5 年前

    有两件事在代码中不起作用:

    for k = j+1:particles

    在parfor中,嵌套循环应具有固定的边界。

    2) pop(ind)

    具体的 在这种情况下,顺序并不重要(但matlab不够聪明,不知道这一点)。

    解决方案,线性化:

    %Dummy data
    numBins = 20;
    binWidth = 2.5;
    particles = 10;
    coords = rand(10,2)*40;
    
    %Initialization
    pop = zeros(1,numBins);
    
    parfor j=1:particles
        r1  = coords(j,:)
        r2  = coords((j+1):end,:)          
        d   = sqrt(sum([r1-r2].^2,2)) % compute each norm at the same time !
        pop = pop + histcounts(ceil(d/binWidth),0:numBins) 
    end
    
        2
  •  1
  •   Cris Luengo    5 年前

    function pop = hist_comp(pop,j,particles,coords,binWidth)
      r1 = coords(j,:);
      for k=j+1:particles
          r2 = coords(k,:);
          d = norm(r1-r2);
          ind = ceil(d/binWidth);
          pop(ind) = pop(ind) + 1;
      end
    end
    
    numBins = 20;
    binWidth = 2.5;
    particles = 10;
    coords = rand(10,2)*5;
    pop = zeros(1,numBins);
    
    
    f = @(pop,j) hist_comp(pop,j,particles,coords,binWidth);
    
    parfor j=1:particles
      pop = f(pop,j);
    end