[英]How to check if each value in a matrix is between the corresponding values in two other matrices in R?
I have a matrix that I would like to compare with two other matrices to see if each entry in my matrix is contained within the values of the other two matrices or outside the values. 我有一个矩阵,我想与其他两个矩阵进行比较,以查看我的矩阵中的每个条目是否包含在其他两个矩阵的值内或值之外。 For example, if my matrix is: 例如,如果我的矩阵是:
> M
[,1] [,2] [,3]
[1,] -0.1278982 0.4600544 1.3271033
[2,] -0.1079272 1.2196851 -0.5240536
[3,] 0.9548449 -0.9979668 -0.6636296
and the other two matrices I have are L and U: 我拥有的另外两个矩阵是L和U:
> L
[,1] [,2] [,3]
[1,] -0.49416022 1.0992247 -1.2834469
[2,] 0.35491793 0.2460946 1.1411529
[3,] 0.01755317 0.2469062 0.2843848
and 和
> U
[,1] [,2] [,3]
[1,] -0.84996737 1.0036554 -0.04747612
[2,] 0.35396050 -0.4612527 -1.47341334
[3,] -0.07716839 -1.5921625 1.62187501
I would like to take each entry of M and compare to see if it is contained within the range made by the corresponding entry of L and U. 我想取M的每个条目并进行比较,看它是否包含在L和U的相应条目所作的范围内。
For example, for M[1,1], it is outside the range of -0.49416022 and -0.84996737, and so I will assign this comparison a value of 0. On the other hand, for M[2,3], the value is -0.5240536 and so is between 1.1411529 and -1.47341334, and so this comparison gets a value of 0. 例如,对于M [1,1],它超出了-0.49416022和-0.84996737的范围,因此我将为该比较赋值0.另一方面,对于M [2,3],该值是-0.5240536,因此介于1.1411529和-1.47341334之间,因此此比较的值为0。
Ultimately, I would like to obtain a matrix of all 0 and 1's, indicating if the entries in M were contained within corresponding values in L and U. For example, if we call this matrix M_comparisons, then: 最后,我想获得一个全0和1的矩阵,表明M中的条目是否包含在L和U中的相应值中。例如,如果我们将此矩阵称为M_comparisons,则:
> M_comparisons
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 1
[3,] 0 1 0
Does anyone have any ideas how I can do this for large matrices and possible in a very fast computational time? 有没有人有任何想法如何为大型矩阵做到这一点,并且可以在非常快的计算时间内完成? Thanks! 谢谢!
As simple as: 很简单:
(M > U & M < L)*1
# [,1] [,2] [,3]
#[1,] 0 0 0
#[2,] 0 0 1
#[3,] 0 1 0
Or, as suggested by Rui Barradas (slightly faster): 或者,正如Rui Barradas所建议的那样(稍快):
as.integer(M > U & M < L)
library(microbenchmark)
microbenchmark(
(M > U & M < L)*1,
as.integer(M > U & M < L)
)
#Unit: microseconds
# expr min lq mean median uq max neval
# (M > U & M < L) * 1 1.278 1.469 2.15965 1.640 1.8000 38.981 100
# as.integer(M > U & M < L) 1.042 1.212 1.59757 1.384 1.5375 12.008 100
M <- t(matrix(c(-0.1278982, 0.4600544, 1.3271033,
-0.1079272, 1.2196851, -0.5240536,
0.9548449, -0.9979668, -0.6636296), nrow = 3))
L <- t(matrix(c(-0.49416022, 1.0992247, -1.2834469,
0.35491793, 0.2460946, 1.1411529,
0.01755317, 0.2469062, 0.284384), nrow = 3))
U <- t(matrix(c(-0.84996737, 1.0036554, -0.04747612,
0.35396050, -0.4612527, -1.47341334,
-0.07716839, -1.5921625, 1.6218750), nrow = 3))
或者另一种方式
+(M > U & M < L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.