Suppose that I have lower triangular matrix ie,
w1 <- c(0,0.6,0.3,0.6,0.7,
0,0,0.6,0.6,0.7,
0,0,0,0.6,0.6,
0,0,0,0,0.7,
0,0,0,0,0)
w1 <- matrix(w1,5,5)
Then, I would like the second matrix to be a lower triangular matrix, say w2
where each non-zero values of w2
are 1-the corresponding values of w1
.
Like this:
w2 <- c(0,0.4,0.7,0.4,0.3,
0,0,0.4,0.4,0.3,
0,0,0,0.4,0.4,
0,0,0,0,0.3,
0,0,0,0,0)
w2 <- matrix(w2,5,5)
w <- list(w1, w2)
How can I get w2
automatically?
由于R中的大多数运算都是矢量化的,因此您可以简单地使用ifelse
减去1 - w1
,或者如果w1
为零,则保留零。
ifelse(w1 == 0, 0, 1 - w1)
You can use the indexing of lower.tri()
also on the left side:
w2new <- matrix(0, dim(w1)[1], dim(w1)[2])
w2new[lower.tri(w2new)] <- 1 - w1[lower.tri(w1)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.