Matrix with a gradient from a specific value to zero
I want to create a matrix that has a maximum value in its "bottom left" corner (for example 10), and has its value in the "bottom right" and "top left" corner 0. The matrix should be filled with values from the maximum value to one, and then with zeros.
##e.g. start with this
m <- matrix(ncol = 10, nrow = 10)
m[,1] <- 1:10
m[10, ] <- 10:1
What is the most efficient way to fill a matrix similarly
## 1 0 0 0
## 2 1 0 0
## 3 2 1 0
## 4 3 2 1
source to share
From what I understood it can be done, for example, like this:
n <- 4
sapply((n:1)-1, "+", 1:n)
# [,1] [,2] [,3] [,4]
# [1,] 4 3 2 1
# [2,] 5 4 3 2
# [3,] 6 5 4 3
# [4,] 7 6 5 4
It can also be viewed as part of the Toeplitz matrix, see ?toeplitz
.
I misunderstood the explanation! The example helped a lot. To match the example, there are many possible solutions.
Solution 1 s toeplitz
n <- 4
M <- toeplitz(1:n)
M[upper.tri(M)] <- 0
M
# [,1] [,2] [,3] [,4]
# [1,] 1 0 0 0
# [2,] 2 1 0 0
# [3,] 3 2 1 0
# [4,] 4 3 2 1
Solution 2 with sapply
andpmax
sapply((1:n)-1, function(i) pmax((1:n)-i, 0) )
# [,1] [,2] [,3] [,4]
# [1,] 1 0 0 0
# [2,] 2 1 0 0
# [3,] 3 2 1 0
# [4,] 4 3 2 1
NB: with a little adjustment pmax
can be placed outside sapply
as in pmax(-sapply((1:n)-1, "-", 1:n),0)
.
source to share
lower.tri(m, diag=T) %*% lower.tri(m, diag=T)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 1 0 0 0 0 0 0 0 0 0
# [2,] 2 1 0 0 0 0 0 0 0 0
# [3,] 3 2 1 0 0 0 0 0 0 0
# [4,] 4 3 2 1 0 0 0 0 0 0
# [5,] 5 4 3 2 1 0 0 0 0 0
# [6,] 6 5 4 3 2 1 0 0 0 0
# [7,] 7 6 5 4 3 2 1 0 0 0
# [8,] 8 7 6 5 4 3 2 1 0 0
# [9,] 9 8 7 6 5 4 3 2 1 0
#[10,] 10 9 8 7 6 5 4 3 2 1
source to share