在matlab中嵌套带有跳过索引的循环的paralelise

时间:2018-10-04 16:03:18

标签: matlab nested-loops parfor

我想在matlab中并行化嵌套的for循环,但是当循环变量跳过值时。我有这样的东西:

  n=10;
  m=10;
  l=10;
  sizze=[n m l];
  nml=prod(sizze);
  %% this matrices are created elsewhere 
  A=ones(n,m,l);
  B=A;
  C=A;
  D=A;
  E=A;
  F=A;
  G=A;
  %% output
  M=sparse(nml,nml);      
  for i=2:n-1
      for j=2:m-1
          for k=2:l-1         
              subscripts=[i j k-1;i j-1 k;i-1 j k;i j k;i+1 j k;i j+1 k;i j k+1];
              inds=batch_sub2ind(sizze,subscripts);
              values=[A(i,j,k) B(i,j,k) C(i,j,k) D(i,j,k) E(i,j,k) F(i,j,k) G(i,j,k)];            

              M(inds(4),inds)=values;
          end
      end
  end      
  %% extra function
  function ind=batch_sub2ind(sizze,M)
  n=size(M,1);
  ind=zeros(1,n);
  for i=1:n
      ind(i)=sub2ind(sizze,M(i,1),M(i,2),M(i,3));
  end

我完成了这样的工作:

  linearidx=[];
  parfor k=2:l-1
    for j=2:m-1
        for i=2:m-1         
            linearidx=[linearidx sub2ind(sizze,i,j,k)];
        end
    end
  end
  linearidx=sort(linearidx);      
  nml2=numel(linearidx);
  I=[];
  J=[];
  V=[];
  parfor ii=1:nml2
    [i,j,k]=ind2sub(sizze,linearidx(ii));
    values=[A(i,j,k) B(i,j,k) C(i,j,k) D(i,j,k) E(i,j,k) F(i,j,k) G(i,j,k)]';
    subscripts=[i j k-1;i j-1 k;i-1 j k;i j k;i+1 j k;i j+1 k;i j k+1];
    inds=batch_sub2ind(sizze,subscripts);
    I=[I;ones(7,1)*linearidx(ii)];
    J=[J;inds];
    V=[V;values];
  end
  M=sparse(I,J,V,nml,nml);

是否有一种更有效的方法(避免使用嵌套的for循环)?

0 个答案:

没有答案