title: How to concatenate mxArray vector efficiently
body: <p>In MATLAB script, we can do</p>
  
  <pre><code>a = [1 2 3]
  a = [a 4]
  </code></pre>
  
  <p>Does internally MATLAB reallocate/copy memory or use reserved memory until it is not big enough? I guess it may do the later to improve performance. It could optimize in this way because MATLAB knows no one refers to the original a after the append.</p>
  
  <p>How can we concatenate mxArray in the same way? mlCreate needs explicit dimension sizes, and mlfVertcat seems returning a new one? I am not sure if mlfVectcat or mlfCat can work w/o reallocation.</p>
  
  <p>We can do the following manually. Does there exist any similar utilities? </p>
  
  <pre><code>class mxDynamicDoubleVector {
  
  public:
      mxDynamicDoubleVector(mwSize reservedSize = 2);
  
      void pushBack(double d);
  
      const mxArray *getData() const {
          return data_;
      }
  
      ~mxDynamicDoubleVector();
  
  private:
      mxDynamicDoubleVector(const mxDynamicDoubleVector&amp;);
      void operator = (const mxDynamicDoubleVector&amp;);
  
      mwSize reservedSize_;    
      mxArray *data_;
  };
  
  mxDynamicDoubleVector::mxDynamicDoubleVector(mwSize reservedSize)
      : reservedSize_(reservedSize)
  {
      data_ = mxCreateUninitNumericMatrix(1, reservedSize_, mxDOUBLE_CLASS, mxREAL);
      mxSetN(data_, 0);
  }
  
  void mxDynamicDoubleVector::pushBack(double d) 
  {   
      mwSize n = mxGetN(data_);
      if (n == reservedSize_) {
          double *ptr = mxGetPr(data_);
          reservedSize_ *= 2;
          ptr = static_cast&lt;double*&gt;(mxRealloc(ptr, sizeof(double) * reservedSize_));
          mxSetPr(data_, ptr);
      }
      double *ptr = mxGetPr(data_);
      ptr[n] = d;
      mxSetN(data_, n+1);
  }
  
  mxDynamicDoubleVector::~mxDynamicDoubleVector() 
  {
      mxDestroyArray(data_);
  }
  </code></pre>