Home > Enterprise >  Values of matrix based on their column and row number in R
Values of matrix based on their column and row number in R

Time:11-24

I have a 30 x 30 matrix in R and I want the values to be multiplied of their column and row number. For example the first value is [1] * [1] = 1

mat2 <- matrix(nrow= 30, ncol = 30)

CodePudding user response:

We can use row and col to get the index of row/columns and use that to multiply

mat2 <- row(mat2) *col(mat2)

CodePudding user response:

If you know the size of the matrix, you can also use outer() and construct the matrix directly in one step.

mat2 <- outer(seq(30), seq(30))

# other simple variations:
outer(1:30, 1:30)
seq(30) %o% seq(30)
1:30 %o% 1:30
  •  Tags:  
  • r
  • Related