Fill a matrix with a circular pattern

I want to write a function that fills the matrix mon m, where it mis odd as follows: 1) it starts with the middle cell of the matrix (for example, for 5 by 5 A, the middle matrix cell is A [2,2]) and puts the number 1 there 2) it goes one cell forward and adds 1 to the previous cell and places it in the second cell 3) it goes down and puts 3, left 4, left 5, up 6, up 7, ... for example, the resulting matrix can be like this:

> 7 8 9 
  6 1 2
  5 4 3

can someone help me implement?

+4
source share
1 answer
max_x=5
len=max_x^2
middle=ceiling(max_x/2)
A=matrix(NA,max_x,max_x)

increments=Reduce(
    f=function(lhs,rhs) c(lhs,(-1)^(rhs/2+1)*rep(1,rhs)),
    x=2*(1:(max_x)),
    init=0
    )[1:len]
idx_x=Reduce(
    f=function(lhs,rhs) c(lhs,rep(c(TRUE,FALSE),each=rhs)),
    1:max_x,
    init=FALSE
    )[1:len]
increments_x=increments
increments_y=increments
increments_x[!idx_x]=0
increments_y[idx_x]=0

A[(middle+cumsum(increments_x)-1)*(max_x)+middle+cumsum(increments_y)]=1:(max_x^2)

gives

#> A
#     [,1] [,2] [,3] [,4] [,5]
#[1,]   21   22   23   24   25
#[2,]   20    7    8    9   10
#[3,]   19    6    1    2   11
#[4,]   18    5    4    3   12
#[5,]   17   16   15   14   13

: increments . 0/+1/-1 // . , . idx_x - , (TRUE), (FALSE). R ( ).


: OP ​​ , increments.

( ). , , 1 , . x=2*(1:(max_x)) rep(1,rhs). /. (). (-1)^(rhs/2+1).

+1

All Articles