Home > OS >  How can i create this exact 5x5 matrix using only matrix operations?
How can i create this exact 5x5 matrix using only matrix operations?

Time:12-10

I was given this matrix and i have to create it using exclusively matrix operations.

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

So this is what i have done, but im not sure if this is actually considered as matrix operations in order to create my MATNew

mat1 <- matrix(c(0:4), nrow=1, ncol=5) ; print(mat1)
mat2 <- matrix(c(1:5), nrow=1, ncol=5) ; print(mat2)
mat3 <- matrix(c(2:6), nrow=1, ncol=5) ; print(mat3)
mat4 <- matrix(c(3:7), nrow=1, ncol=5) ; print(mat4)
mat5 <- matrix(c(4:8), nrow=1, ncol=5) ; print(mat5)

MATNew <- matrix(cbind(mat1,mat2,mat3,mat4,mat5), 5, 5) ; print(MATNew)

CodePudding user response:

outer(0:4, 0:4, ` `)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    2    3    4
# [2,]    1    2    3    4    5
# [3,]    2    3    4    5    6
# [4,]    3    4    5    6    7
# [5,]    4    5    6    7    8

CodePudding user response:

You can use the row() and col() functions (if this is homework, make sure to cite your sources ...)

m <- matrix(NA, 5, 5)
row(m)   col(m)-2

CodePudding user response:

A matrix-only solution

matrix( rep(0:8,5), 5 )[,1:9%%2==1]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    1    2    3    4    5
[3,]    2    3    4    5    6
[4,]    3    4    5    6    7
[5,]    4    5    6    7    8

CodePudding user response:

Try this?

> embed(0:8, 5)[, 5:1]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    3    4
[2,]    1    2    3    4    5
[3,]    2    3    4    5    6
[4,]    3    4    5    6    7
[5,]    4    5    6    7    8

CodePudding user response:

Benchmark for kicks:

microbenchmark::microbenchmark(
  outer = outer(0:4, 0:4, ` `),
  rowcol = {m <- matrix(NA, 5, 5); row(m)   col(m)-2},
  matrix1 = matrix(rep(0:8,5), 5)[,1:9%%2==1],
  matrix2 = matrix(rep(0:8,5), 5)[,c(TRUE, FALSE)],
  matrix3 = matrix(rep(0:4, each = 5)   0:4, 5),
  sequence = matrix(sequence(rep(5, 5), 0:4), 5), times = 1e5)
#> Unit: microseconds
#>      expr   min    lq     mean median    uq      max neval
#>     outer 5.100 6.200 8.706730  6.501 7.202 6628.401 1e 05
#>    rowcol 2.900 3.801 5.097179  4.002 4.402 4985.501 1e 05
#>   matrix1 2.900 3.701 5.159770  4.000 4.400 3621.901 1e 05
#>   matrix2 2.400 3.002 4.063637  3.201 3.601 2395.001 1e 05
#>   matrix3 2.000 2.600 3.535451  2.701 3.001 2517.101 1e 05
#>  sequence 3.701 4.601 6.179183  4.901 5.401 3303.102 1e 05
  • Related