title: Matlab memory leak when forward propagating cell arrays or 3D matrices
body: <p>I'm having an issue with the way Matlab is dealing with forward multiplying matrices when there are a large number of them. </p>
  
  <p>As a simplified example, i'd like to do x(ii + 1) = y(ii) * x(ii). However when the dimensions of the matrix are large, and there are a lot of them, the memory requirement grows exponentially, way out of range for what it should be. </p>
  
  <p>Here's some example code, where according to the matlab memory profiler it's using 1e-07TB of RAM, which although isn't correct this loop often takes up 256GB of RAM. </p>
  
  <pre><code>function forward_test()
      K = 250; 
      dim = 1024;
      U = cell(K,1);
  
      for ii = 1 : K 
          U{ii} = rand(dim,dim) + (1i*rand(dim,dim));
      end
  
      r_tmp = cell(K + 1, 1); r_tmp{1} = eye(dim);
      for k = 1 : K 
          r_tmp{k+1} = U{k} * r_tmp{k}; % &lt;--- this line is the issue
      end
  
      % convert the matrix to a 3D array, I'm certian there's a better way of doing this, but this is quick and dirty
      u_test = zeros(dim, dim, K);
      for ii = 1 : K
          u_test(:,:,ii) = U{ii};
      end
  
      % test the same operation on a 3D array, rather than a set of 2D maricies. 
      tmp2 = zeros(dim, dim, K + 1); tmp2(:,:,1) = eye(dim);
      for ii = 1 : K
          tmp2(:,:, ii + 1) =  U{ii} * tmp2(:,:,ii);
      end 
  
  
      for ii = 1 : numel(r_tmp)
          if ~(all(all(r_tmp{ii} == tmp2(:,:,ii))))
              error('Result missmatch!');
          end
      end
  end
  </code></pre>
  
  <p>To check performance run:</p>
  
  <pre><code>profile off
  profile -memory on
  forward_test
  profreport
  </code></pre>