title: How to improve the speed of gather() function in MATLAB, or this is an alternative method to transfer data from gpuArray to general array?
body: <p>I wrote an algorithm to solve a set of PDE. There are some very long equations in the middle of while loop, and I tried to calculated these equations by GPU for speeding up, then the results from these equations are further employed. It runs successful, however, the <code>gather()</code> function takes almost 1/5 of total time (3000s). I tried to use <code>[dk1,dk2,dk3,dk4,dk5,dk6,dk7,dk8,dk9] = dkfunction(S,T)</code> in command window, it just cost 0.001s.</p>
  <p>I am confused why this code in a big loop performs badly? I want to know if there is a way to speed up <code>gather()</code> function, or an alternative function? By the way, the size of array in mex file should be constant or not?</p>
  <p>(Note: my code is very long, so I attatch the profiler and core part (simplified) of my question. <code>dkfunction</code> is related to cuda).</p>
  <p>Profiler for following code operation time:</p>
  <p><a href="https://i.stack.imgur.com/68wwi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/68wwi.png" alt="enter image description here" /></a></p>
  <pre><code>while t&lt;n  
  
     %Omitted code for S and T calculation.
     %%%
  [dk1,dk2,dk3,dk4,dk5,dk6,dk7,dk8,dk9] = dkfunction(S,T); 
  
  [dkvTdT,dkvTdS,dkvhdT,dkvhdS,dphaivdT,dphaivdS,dkhdS,dkdS,dphaidS] = gather(dk1,dk2,dk3,dk4,dk5,dk6,dk7,dk8,dk9);
     %%%
     %Omitted code to use dkvTdt..... to calculate other variables and t steps.
     %%%
  
  end
  </code></pre>