Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

Two-circulant matrix in R

How to construct a two-circulant matrix?

For example, the following matrix A is two-circulant, i.e every column (expect from the first one) is obtained from the previous one by putting the last two elements as first. Note that the first column is the generator of the matrix.

N=12
k=6
x=c(0,0,0,0,1,1,1,1,2,2,2,2)
A=matrix(0,N,k)
A[,1]=x
for( j in 2:ncol(A) )
{
A[,j]=c(A[11:12,j-1],A[1:10,j-1])
}

> A
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    0    2    2    1    1    0
 [2,]    0    2    2    1    1    0
 [3,]    0    0    2    2    1    1
 [4,]    0    0    2    2    1    1
 [5,]    1    0    0    2    2    1
 [6,]    1    0    0    2    2    1
 [7,]    1    1    0    0    2    2
 [8,]    1    1    0    0    2    2
 [9,]    2    1    1    0    0    2
[10,]    2    1    1    0    0    2
[11,]    2    2    1    1    0    0
[12,]    2    2    1    1    0    0

Is there any other way to constuct the matrix A? For example by using a function.

Upvotes: 1

Views: 90

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

You could use the following:

circular_matrix <- function(x, ncol) {

 coll <- list(x)
 for (i in 1:(ncol-1)) {

  current <- coll[[length(coll)]]
  coll[[length(coll) + 1]] <- c(tail(current, 2), current[1:(length(current) - 2)])

 }

 do.call(cbind, coll)

}

circular_matrix(1:10, 5)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    9    7    5    3
# [2,]    2   10    8    6    4
# [3,]    3    1    9    7    5
# [4,]    4    2   10    8    6
# [5,]    5    3    1    9    7
# [6,]    6    4    2   10    8
# [7,]    7    5    3    1    9
# [8,]    8    6    4    2   10
# [9,]    9    7    5    3    1
#[10,]   10    8    6    4    2

Upvotes: 1

Related Questions