title: Octave force deepcopy
body: <h2>The question</h2>
  
  <p>What are the ways of coercing octave to create a real copy of whatever object? Structures are the main interest.</p>
  
  <h2>My underlying problem</h2>
  
  <p>In my problem I'm obtaining a rather large structure from another function in a loop but for the current task only a few pieces of it are needed. For example:</p>
  
  <pre><code>for i=1:many
      res=solver(params);
      store1{i}=res.string1;
      store2{i}=res.arr(:,1);
  end
  </code></pre>
  
  <p><code>res</code> is a sizable chunk of data and due to lazy-copy those <code>store</code>-s are references to tiny portions of bytes in that chunk. After I store those tiny portions, I don't need <code>res</code> itself, however, since middle of that chunk is referenced by <code>store</code>, the memory area is unfit for <code>res</code> obtained on the next iteration (they are of the same size) and thus another sizable piece of memory is allocated, which is then again crossed by few tiny links an so on.</p>
  
  <p>Without storing parts of res, the program successfully keeps the memory consumption same after first couple of iterations.</p>
  
  <p>So how do I make a complete copy of structure field?
  I've tried using <code>struct</code>-related functions like <code>rmfield</code> but those keep references instead of their own objects.
  I've tried to wrap the assignment of  in its own function:
      new_struct=copy( rmfield(old_struct,"bigdata"));
      function c=copy(a);
          c=a;
      end;
  This by the way doesn't work even for arrays.
  I'm interested in method applicable to any generic variable.</p>
  
  <h2>Minimal working example of the problem</h2>
  
  <pre><code>a=cell(3,1); 
  for i=1:length(a); 
      r=rand(100000,1000);
      a{i}=r(1:100,end);
      whos; fflush(stdout);
      pause(2); 
  end;
  </code></pre>
  
  <p>The above code will cause memory usage to gradually grow by far more than 8.08 kb reported by <code>whos</code> due to references stored by <code>a{i}</code> blocking bigger memory block than they actually need. If you force the proper copy, the problem is not present.</p>