title: Go faster than cell2mat
body: <p>I'm optimizing some code at the moment and can't figure out a way to go faster than MATLAB's <code>cell2mat</code>. For now, the multiple uses of <code>cell2mat</code> in my code <strong>represent more than 15% of the processing time</strong>.</p>
  
  <p>I think it can go faster than that, because i know the structure of the cell arrays i'll pass to the function.</p>
  
  <p>Basically, the cell array is <code>NxN</code>, where : </p>
  
  <ol>
  <li><p>The top left <code>(N-1)x(N-1)</code> block contains, in each cell, a <code>6x6</code> double matrix</p></li>
  <li><p>The bottom right <code>(N,N)</code> cell is a <code>MxM</code> double matrix.</p></li>
  <li><p>The other cells have the right dimensions for concatenating, i.e. :</p></li>
  </ol>
  
  <p>The cells <code>(1:(N-1),N)</code> are <code>6xM</code> double matrices, the cells <code>(N,1:(N-1))</code> are <code>Mx6</code> double matrices. (Image added for the sake of clarity, there <code>N=207</code> and <code>M=300</code>)</p>
  
  <p><a href="https://i.stack.imgur.com/8X28K.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8X28K.jpg" alt="enter image description here"></a></p>
  
  <p>As the cells will always be filled with doubles AND always be of dimension 2, i'm already only using a small piece of the <code>cell2mat</code> code, i.e. :</p>
  
  <pre><code> function m = myCell2Mat(c)
  
      rows = size(c,1);
  
  
          m = cell(rows,1);
          % Concatenate one dim first
          for n=1:rows
              m{n} = cat(2,c{n,:});% 73% of the time spent here
          end
          % Now concatenate the single column of cells into a matrix
          m = cat(1,m{:});% 25.2% of the time spent there
  
  
    end
  </code></pre>
  
  <p>This doens't change the time spent much as (like one could imagine), the most time is spent on these lines.</p>
  
  <p><strong>My question is :</strong> Does anyone have an idea about how to remove the loop there? I tried something along the lines of :</p>
  
  <pre><code>N=207;
  M=300;
  C=cell(N,N);
  for ii=1:N-1
    for jj=1:N-1
  C{ii,jj}=rand(6);
    end
  end
  
  for kk=1:(N-1)
  C{N,kk}=rand(M,6);
  C{kk,N}=rand(6,M);
  end
  
  C{end}=rand(M,M);
  
  tmp1=cat(1,C{:,1:(end-1)});
  LeftPart=reshape(tmp1,[],6*(size(C,2)-1));
  
  RightPart=cat(1,C{:,end});
  
  Res=[LeftPart RightPart];
  </code></pre>
  
  <p>But it doesn't show any improvment in time.. (And gives a false result as the <code>reshape</code> operates columnwise)</p>
  
  <p>I've thought about using a recursive function aswell but it doesn't seem to be going anywhere.</p>
  
  <p>Thanks in advance!</p>