1
votes

I have a 3 nested for loop that produces a vector, but each time it runs through the loops the vector that is produced changes size. I need to save each of these vectors at the ended of the for loops, so I was thinking of using mat2cell and store them in a cell. But I don't know the code get out a cell vector that will contain each of these different sized vectors.

I will give an example code

for ip = n_low:n_up
    for jx = x_low:x_up
        for jphi = phi_lowx:phi_upx
            lx = find_path(ip,jx,jphi,0,1);
           .
           .
           .
           A_r = volumeintegrate(integr_final_r , r , z , phi);
       end
   end
end

Obviously, you don't know what these variables are or the numbers but I think its not needed to solve the problem. Anyways A_r is what is spit out at the end of the loops, but A_r varies in size as the loop repeats itself. I need to save every A_r vector.

2

2 Answers

2
votes

Add a counter and save to a cell element: for example:

counter=0
for ...
   for ...
      for ...
          counter=counter+1;
          A_r{counter} = volumeintegrate(integr_final_r , r , z , phi);

then to extract the n-th vector just write A_r{n}

2
votes

Just create a cell array:

A_r = cell(Ni, Nj, Nk)

Then create loops - note I am indexing over well behaved integers which I will use as index into my cell array, then computing the actual value for the variables you need by looking at the array iVec etc:

iVec = n_low:n_up;
Ni = numel(iVec);
jVec = x_low:x_up;
Nj = numel(jVec);
kVec = phi_lowx:phi_upx;
Nk = numel(kVec);

A_r = cell(Ni, Nj, Nk);

for ii = 1:Ni
  ip = iVec(ii);
  for jj = 1:Nj
    jx = jVec(jj);
    for kk = 1:Nk
      jphi = kVec(kk);
      lx = find_path(ip,jx,jphi,0,1);
      ....
      A_r{ii,jj,kk} = volumeintegrate(integr_final_r , r , z , phi);;
    end
  end
end

You can now access each array in the same way that it was assigned:

A_r{ii,jj,kk}