title: How do I properly "slice" a 4D matrix in Matlab in a parfor loop?
body: <p>I am trying to make a portion of my code run faster in MatLab, and I'd like to use parfor. When I try to, I get the following error about one of my variables <code>D_all</code>.</p>
  
  <p>"The PARFOR loop cannot run because of the way D_all is used".</p>
  
  <p>Here is a sample of my code.</p>
  
  <pre><code>M = 161;
  N = 24;
  P = 161;
  
  parfor n=1:M*N*P
     [j,i,k] = ind2sub([N,M,P],n);
  
     r0 = Rw(n,1:3);
     R0 = repmat(r0,M*N*P,1);
  
     delta = sqrt(dXnd(i)^2 + dZnd(k)^2);
  
     d = R_prime - R0;
  
     inS = Rw_prime(find(sqrt(sum(d.^2,2))&lt;0.8*delta),:);
  
     if isempty(inS)
              D_all(j,i,k,tj) = D_all(j,i,k,tj-1);
     else
              y0 = r0(2);
  
              inC = inS(find(inS(:,2)==y0),:);
  
              dw = sqrt(sum(d(find(sqrt(sum(d.^2,2))&lt;0.8*delta &amp; d(:,2)==0),:).^2,2));
  
              V_avg = sum(dw.^(-1).*inC(:,4))/sum(dw.^(-1));
  
              D_all(j,i,k,tj) = V_avg;
     end
  end
  </code></pre>
  
  <p>I'm not very familiar with parallel computing, and I've looked at the guides online and don't really understand how to apply them to my situation. I guess I need to "slice" <code>D_all</code> but I don't know how to do that.</p>
  
  <p><strong>EDIT</strong>: I think I understand that the major problem is that when using <code>D_all</code> I have <code>tj</code> and <code>tj-1</code>.</p>
  
  <p><strong>EDIT 2</strong>: I don't show this above, it probably would have been helpful, but I defined <code>D_all(:,:,:,1) = V_1;</code> where <code>V_1</code> corresponds to a previous time step. I tried making multiple variables <code>V_2</code>, <code>V_3</code>, etc. for each step and replacing <code>D_all(j,i,k,tj-1)</code> with <code>V_1(j,i,k)</code>. This still led to the same error I am seeing with <code>D_all</code>.</p>
  
  <p>"Valid indices for D_all are restricted for PARFOR loops"</p>