[英]R reverse lower triangle matrix loop
I am trying to fill the lower diagonal of my matrix M with a prefilled vector, V 我试图用预先填充的矢量V填充矩阵M的下对角线
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: 如果我使用lower.tri
函数它会给出一个错误,所以我构建了一个循环,它只应填充来自buttom的列:
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? 什么是最好的方式?
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: 要填充的矩阵部分是原始下三角矩阵相对于行方向的反映,因此您可以将rev
函数应用于lower.tri()
结果以反转每一行以获取索引替换元素,然后它会很简单:
Assuming you have matrix M
and vector v
: 假设你有矩阵M
和向量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
We can do it this way: 我们可以这样做:
Define a full matrix with the values of v to be inserted 使用要插入的v值定义完整矩阵
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 现在我们可以用替换矩阵中相应的值替换M中列大于行的反向的元素
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.