Reputation: 49
I am trying to fill the lower diagonal of my matrix M with a prefilled vector, V
My original matrix looks like similar to this:
M = matrix(c(.3,.2,.1,0), nrow=4, ncol=5)
M 1 2 3 4 5
1 .3 .3 .3 .3 .3
2 .2 .2 .2 .2 .3
3 .1 .1 .1 .1 .1
4 0 0 0 0 0
I have a vector similar to this:
V
.4
.3
.25
.1
Now I want to fill the lower triangle with this vector, to get:
0 1 2 3 4 5
1 .3 .3 .3 .3 .1
2 .2 .2 .2 .25 .25
3 .1 .1 .3 .3 .3
4 0 .4 .4 .4 .4
If I use the lower.tri
function it gives out an error so I built a loop which only should fill the columns from the buttom up:
o <- 5
c <- 2
s <- 1
for(s in (1:o)){
for(c in (2:o)){
M[((o-s):o),c] <- V[1:c]}}
My idea was to move upwards like I manually wrote:
M[(5-1):5,2] <- V[1:2]
M[(5-2):5,3] <- V[1:3]
What's the best way?
Upvotes: 1
Views: 686
Reputation: 31454
We can do it this way:
Define a full matrix with the values of v to be inserted
N = matrix(rev(v), 4, 5)
Now we can replace elements in M whose column is greater than the reverse of the row with corresponding value in the replacement matrix
R = rev(row(M))
C = col(M)
M[C>R] = N[C>R]
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0.3 0.3 0.3 0.30 0.10
# [2,] 0.2 0.2 0.2 0.25 0.25
# [3,] 0.1 0.1 0.3 0.30 0.30
# [4,] 0.0 0.4 0.4 0.40 0.40
Upvotes: 1
Reputation: 215107
The part of the matrix you want to fill is a reflection of the lower triangular matrix of the original one with respect to row direction, so you can apply a rev
function to the lower.tri()
result to reverse every row to get the index for replacing the elements, and then it would be straightforward:
Assuming you have matrix M
and vector v
:
M
# X1 X2 X3 X4 X5
#1 0.3 0.3 0.3 0.3 0.3
#2 0.2 0.2 0.2 0.2 0.3
#3 0.1 0.1 0.1 0.1 0.1
#4 0.0 0.0 0.0 0.0 0.0
v
# [1] 0.40 0.30 0.25 0.10
lowerIndex = t(apply(lower.tri(M, diag = TRUE), 1, rev))
M[lowIndex] <- (lowIndex * rev(v))[lowIndex]
M
# X1 X2 X3 X4 X5
#1 0.3 0.3 0.3 0.30 0.10
#2 0.2 0.2 0.2 0.25 0.25
#3 0.1 0.1 0.3 0.30 0.30
#4 0.0 0.4 0.4 0.40 0.40
Upvotes: 2