title: Efficient way to create a circulant matrix in R
body: <p>I want to create a circulant matrix from a vector in R. A circulant matrix is a matrix with the following form.</p>
  
  <pre><code>1 2 3 4
  4 1 2 3
  3 4 1 2
  2 3 4 1
  </code></pre>
  
  <p>The second row is the same as the first row except the last element is at the beginning, and so on.</p>
  
  <p>Now I have the vector, say, (1, 2, 3, 4) and I want to find a efficient (fast) way to create this matrix. In practice, the numbers are not integers and can be any numbers.</p>
  
  <p>Here is what I am doing now.</p>
  
  <pre><code>x &lt;- 1:4
  n &lt;- length(x)
  mat &lt;- matrix(NA, n, n)
  for (i in 1:n) {
      mat[i, ] &lt;- c(x[-(1:(n+1-i))], x[1:(n+1-i)])
  }
  </code></pre>
  
  <p>I wonder if there is a faster way to do this? I need to generate this kind of matrices over and over. A small improvement for one step will make a big difference. Thank you.</p>