Barış Babahan
Barış Babahan

Reputation: 74

Create nxn matrix

For example, if the user entered 5, the matrix will be like fpllowing:

1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
4,5,6,7,8
5,6,7,8,9

Upvotes: 0

Views: 321

Answers (2)

akrun
akrun

Reputation: 887951

We can use sapply

n <- 5
sapply(seq_len(n), `+`, seq_len(n) -1)

-output

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    2    3    4    5    6
#[3,]    3    4    5    6    7
#[4,]    4    5    6    7    8
#[5,]    5    6    7    8    9

Or use outer

outer(seq_len(n), seq_len(n)-1, `+`)

If we need a for loop

m1 <- matrix(0, n , n)
for(i in seq_len(n)) {
    for(j in seq_len(n)) {
   
     m1[i, j] <- i +  (j - 1)
 }
}

-output

m1
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    2    3    4    5    6
#[3,]    3    4    5    6    7
#[4,]    4    5    6    7    8
#[5,]    5    6    7    8    9

Or using a single for loop

m1 <- matrix(0, n , n)
s1 <- seq_len(n)

for(i in s1) m1[i,] <- s1 + (i-1)

Or another option with embed

embed(c(1:9, 1:9), n)[s1, rev(s1)]

Upvotes: 1

Onyambu
Onyambu

Reputation: 79348

Another quick way could be:

 x <- diag(5)
 row(x) + col(x) - 1

Upvotes: 3

Related Questions