title: Return a reference to a Armadillo vector element
body: <p>I am having a hard time determining how to return a reference to an element of an armadillo vector.</p>
  
  <p>e.g.</p>
  
  <pre><code>arma::vec3 v = arma::zeros(3);
  v.at(0) = 1; // works as expected, surely this means the at() method returns a reference?
  </code></pre>
  
  <p>however this does not compile:</p>
  
  <pre><code>struct Custom {
    arma::vec3 v;
    double&amp; x() { return v.at(0) }
  }
  Custom custom;
  custom.x() = 1;
  </code></pre>
  
  <p>The error is as follows:</p>
  
  <blockquote>
    <p>error: invalid initialization of reference of type ‘double&amp;’ from expression of type ‘const double’</p>
  </blockquote>
  
  <p>I assume this is because at() returns a copy instead of a reference, but then how does the previous example work?</p>
  
  <p>I believe this may be because of armadillo's glue types that are returned rather than a real 'double', but I can't find any documentation on these so I'm unsure how to use them.</p>
  
  <hr>
  
  <p><strong>Answer</strong></p>
  
  <p>The below methods work, giving 'reference-like' named access to the vector elements.</p>
  
  <pre><code>inline double x() const { return at(0); }
  inline double&amp; x() { return at(0); }
  
  inline double y() const { return at(1); }
  inline double&amp; y() { return at(1); }
  
  inline double z() const { return at(2); }
  inline double&amp; z() { return at(2); }
  
  inline const arma::subview_col&lt;double&gt; xy() const { return rows(0,1); }
  inline arma::subview_col&lt;double&gt; xy() { return rows(0,1); }
  </code></pre>