如何在 R 数组中将包括主对角线在内的下三角矩阵设置为零?
存储在数组中的矩阵不能直接在下三角或上三角位置设置为零,因为数组中的赋值并非直截了当。因此,要将存储在 R 数组中的下三角矩阵设置为零,我们可以使用 for 循环。
查看以下示例以了解如何操作。
示例
以下代码片段创建一个示例数组:
Array<-array(rnorm(5*5*4),dim=c(5,5,4)) Array
创建以下数组:
, , 1 [,1] [,2] [,3] [,4] [,5] [1,] 0.70981523 -2.4078489 0.39454174 0.1926095 -1.0898185 [2,] -0.14475044 0.6219629 -0.95420653 0.4479287 -0.3779962 [3,] 0.01167506 2.1993791 0.07737409 0.6061328 -1.0125574 [4,] 0.79220776 -0.5975221 0.88549417 1.0882225 -0.5481808 [5,] 0.29491262 1.4220833 0.07935382 -1.0755292 0.7970269 , , 2 [,1] [,2] [,3] [,4] [,5] [1,] 0.8094188 0.4551336 -0.7160230 0.6137609 0.43214122 [2,] 0.5074892 1.4076603 1.1292408 -2.7777503 1.41570799 [3,] -0.6848127 -1.2551047 1.4707569 -0.3999298 0.02225272 [4,] -0.8430235 -1.0603518 1.0039837 -1.1010674 -0.73765708 [5,] 2.1778090 -0.2433661 -0.7438562 -0.4833542 1.45107435 , , 3 [,1] [,2] [,3] [,4] [,5] [1,] 1.3963751 0.552293381 0.9465197 0.45676297 0.814354214 [2,] -1.9652982 -0.007544944 1.0610379 -0.50206274 -1.408469903 [3,] 0.5089749 0.129974481 -1.6970820 -1.26033470 0.134300795 [4,] -0.7690704 0.796328881 0.2983638 0.09370386 0.092306831 [5,] 0.8453528 0.103282791 -0.7055156 0.35558281 -0.008647578 , , 4 [,1] [,2] [,3] [,4] [,5] [1,] 0.90802766 -0.4069328 -1.5392820 1.0841168 -0.1180422 [2,] -0.04871904 0.3874517 0.9413034 -0.5000461 -0.7223448 [3,] 0.85111729 -1.6321968 -1.1475875 0.5568671 -0.2763780 [4,] 0.67846366 -1.0864209 -1.1823581 -0.2222426 -0.4751920 [5,] -1.87861268 0.5262939 0.1984496 -0.4013330 0.2765006
现在,为了将数组中的上三角矩阵(包括主对角线)设置为零,请将以下代码添加到上面的代码片段中:
Array<-array(rnorm(5*5*4),dim=c(5,5,4)) for(i in seq(dim(Array)[3])) Array[,,i][lower.tri(Array[,,i],diag=TRUE)]<-0 Array
输出
如果将以上所有代码片段作为一个程序执行,则会生成以下输出:
, , 1 [,1] [,2] [,3] [,4] [,5] [1,] 0 -2.407849 0.3945417 0.1926095 -1.0898185 [2,] 0 0.000000 -0.9542065 0.4479287 -0.3779962 [3,] 0 0.000000 0.0000000 0.6061328 -1.0125574 [4,] 0 0.000000 0.0000000 0.0000000 -0.5481808 [5,] 0 0.000000 0.0000000 0.0000000 0.0000000 , , 2 [,1] [,2] [,3] [,4] [,5] [1,] 0 0.4551336 -0.716023 0.6137609 0.43214122 [2,] 0 0.0000000 1.129241 -2.7777503 1.41570799 [3,] 0 0.0000000 0.000000 -0.3999298 0.02225272 [4,] 0 0.0000000 0.000000 0.0000000 -0.73765708 [5,] 0 0.0000000 0.000000 0.0000000 0.00000000 , , 3 [,1] [,2] [,3] [,4] [,5] [1,] 0 0.5522934 0.9465197 0.4567630 0.81435421 [2,] 0 0.0000000 1.0610379 -0.5020627 -1.40846990 [3,] 0 0.0000000 0.0000000 -1.2603347 0.13430080 [4,] 0 0.0000000 0.0000000 0.0000000 0.09230683 [5,] 0 0.0000000 0.0000000 0.0000000 0.00000000 , , 4 [,1] [,2] [,3] [,4] [,5] [1,] 0 -0.4069328 -1.5392820 1.0841168 -0.1180422 [2,] 0 0.0000000 0.9413034 -0.5000461 -0.7223448 [3,] 0 0.0000000 0.0000000 0.5568671 -0.2763780 [4,] 0 0.0000000 0.0000000 0.0000000 -0.4751920 [5,] 0 0.0000000 0.0000000 0.0000000 0.0000000
广告