title: Access column of matrix without creating copy of data, using Armadillo library
body: <p>I have a (data/storage) class with a member <code>arma::mat</code> (a matrix), and I want to access just one column of this matrix (<code>arma::colvec</code>), but I don't want to create a copy of the data in the column. Is there any way of achieving this?</p>
  
  <p>My first try was using <code>.col(i)</code>, but this returns a temporary, so taking a reference doesn't work.</p>
  
  <p>Using <code>.colptr(i)</code> doesn't create a copy, but it also returns a <code>double*</code> instead of a <code>vec</code>, so it makes my life a bit hard.</p>
  
  <pre><code>struct Data
  {
      mat A;
  
      /* constructors etc. */
  
      // reference to temporary (this is bad)
      const vec&amp; getColumn(const uint i) { return A.col(i); }
  
      // doesn't create a copy, but doesn't return a vec either
      const double* getColumn2(const uint i) const { return A.colptr(i); }
  }
  </code></pre>
  
  <p>The reason for wanting this is that the class has both vectors and matrices, and I want to make uniform getter and setter methods that access either one of the vectors, or a column in a matrix, depending on an index (for iteration purposes).</p>
  
  <p>An example:</p>
  
  <pre><code>struct Data
  {
      mat A;
      vec b;
  
      // getter
      const vec&amp; operator()(const uint i) const
      {
          if (i == 0)
          {
              return b;
          }
          else if (i == 1)
          {
              // return first column of A
          }
          // etc.
      }
  
      // setter
      vec&amp; operator()(const uint i)
      {
          // similar to above
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Solution</h2>
  
  <p>Based on the <a href="https://stackoverflow.com/a/35984246/1850917">answer by zauguin</a> I found the following way to achieve the wanted functionality:</p>
  
  <pre><code>struct Data
  {
      mat A;
      vec b;
  
      // getter
      subview_col&lt;mat::elem_type&gt; operator()(const uint i)
      {
          if (i == 0)
          {
              return b.col(0);
          }
          else if (i &gt; 0 &amp;&amp; i &lt; (1 + A.n_cols()))
          {
              return A.col(i - 1);
          }
          else
          {
              // should probably do some error checking here
          }
      }
  
      // setter
      vec&amp; operator()(const uint i)
      {
          // same as the above, but without consts in declaration
      }
  }
  </code></pre>
  
  <p>This returns <code>subview_col&lt;mat::elem_type&gt;</code> instead of <code>vec</code>, but the functionality is similar/identical for my purposes. I am not sure of the performance impact of using <code>.col(0)</code> on a <code>vec</code>, but I'm not that worried.</p>