MATLAB“parfor”循环中单元阵列功能的故障分类

时间:2017-03-01 16:39:04

标签: matlab parallel-processing parfor

所以我整个上午一直在做研究,无法弄清楚为什么这段代码不会运行。

最初的代码是:

nSim = 100;
nTs = 40;
nRep = 10;
m1 = NaN(nTs,nSim);
meanM1 = NaN(nTs,nRep);
delta = [1/400,1/400,-1/400]';
d = -0.05;
dataQCell = cell(nSim*nRep,1);
for jj=1:nSim*nRep
  dataQCell{jj} = rand(3,nTs);
end

matlabpool('open',10)
parfor ii=1:nRep
  for jj=1:nSim
    for tt=1:nTs
      if tt>1
        m1(tt,jj) = m1(tt-1,jj) + delta'* dataQCell{(ii-1)*nSim+jj,1}(1:3,tt)+d;
      else
        m1(tt,jj) = delta'* dataQCell{(ii-1)*nSim+jj,1}(1:3,tt) + d;
      end
    end
  end

  meanM1(tt,ii) = mean(m1,2);
end
matlabpool close force

我最初的想法是罪魁祸首

m1(tt,jj) = m1(tt-1,jj) + deltaQ'* dataQCell{(ii-1)*nSim+jj,1}(1:3,tt) + d;

因为dataQCell的索引是索引(iijj)的函数。

注意我已注释掉meanM1行,但仍然会收到相同的错误。

我首次尝试解决方案是通过修改代码将{nSim*nRep X 1)单元格分成nRep个部分

nSim = 100;
nTs = 40;
nRep = 10;
m1 = NaN(nTs,nSim);
meanM1 = NaN(nTs,nRep);
deltaQ = [1/400,1/400,-1/400]';
d = -0.05;

dataQCell = cell(nSim*nRep,1);
for jj=1:nSim*nRep
  dataQCell{jj} = rand(3,nTs);
end

dataRepCell = cell(nRep,1);
for ii=1:nRep
  dataRepCell{ii} = dataQCell{(ii-1)*nSim+1:ii*nSim};
end

matlabpool('open',10)
parfor ii=1:nRep
  for jj=1:nSim
    for tt=1:nTs
      if tt>1
        m1(tt,jj) = m1(tt-1,jj) + deltaQ'* dataRepCell{ii}{jj}(1:3,tt)+d;
      else
        m1(tt,jj) = deltaQ'* dataRepCell{ii}{jj}(1:3,tt) + d;
      end
    end
  end

  meanM1(tt,ii) = mean(m1,2);
end
matlabpool close force

但我得到的相同“无法对变量'm1'进行分类”,错误。

1 个答案:

答案 0 :(得分:0)

问题是m1不允许被归类为临时变量,因为我在parfor循环之前预先分配了矩阵。解决方案是在m1=Nan(nTs,nSim)循环内运行parfor