Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R filling matrix element from edge

I have a problem with making matrix

The problem has this condition: if I get size of matrix like n by m, i should return matrix that is filled with integer from 1 to n*m.

fill_matrix = function(n,m){
  #i want to fill but don't know how.......
  return(mat)
}
 > fill_matrix(5,5)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   16   15   14   13
[2,]    2   17   24   23   12
[3,]    3   18   25   22   11
[4,]    4   19   20   21   10
[5,]    5    6    7    8    9

at first time, it seems possible by using direction_change_vector(ex, down : i+1, right:j+1....) or recursion, but i can't get exact result.

If somebody has good idea, plz let me know......

I'm, so frustrated with this problem.

Thank you.

like image 376
Jiwon Kim Avatar asked Jan 18 '26 19:01

Jiwon Kim


1 Answers

I think the problem in your question is looking for a spiral matrix. It has various implementation ways. Here is one iteration-based approach to make such a spiral matrix as you requested

Code

# n and m deonte matrix row and column numbers, respectively
SpiralMatrix <- function(n, m) {
    mat <- matrix(NA, n, m)
    N <- m*n
    u <- l <- 1
    d <- n
    r <- m
    idx <- 1
    while (u <= d && l <= r) {
        # up to down
        for (i in u:d) {
            mat[i, l] <- idx
            if (idx == N) {
                return(mat)
            }
            idx <- idx + 1
        }
        l <- l + 1
        # left to right
        for (i in l:r) {
            mat[d, i] <- idx
            if (idx == N) {
                return(mat)
            }
            idx <- idx + 1
        }
        d <- d - 1
        # down to up
        for (i in d:u) {
            mat[i, r] <- idx
            if (idx == N) {
                return(mat)
            }
            idx <- idx + 1
        }
        r <- r - 1
        # right to left
        for (i in r:l) {
            mat[u, i] <- idx
            if (idx == N) {
                return(mat)
            }
            idx <- idx + 1
        }
        u <- u + 1
    }
}

Output Examples

> SpiralMatrix(3, 4)
     [,1] [,2] [,3] [,4]
[1,]    1   10    9    8
[2,]    2   11   12    7
[3,]    3    4    5    6

> SpiralMatrix(5, 3)
     [,1] [,2] [,3]
[1,]    1   12   11
[2,]    2   13   10
[3,]    3   14    9
[4,]    4   15    8
[5,]    5    6    7

> SpiralMatrix(4, 4)
     [,1] [,2] [,3] [,4]
[1,]    1   12   11   10
[2,]    2   13   16    9
[3,]    3   14   15    8
[4,]    4    5    6    7
like image 114
ThomasIsCoding Avatar answered Jan 21 '26 09:01

ThomasIsCoding