如果R中包含负值,如何找到带符号矩阵的绝对最大值?
如果矩阵中有正值和负值,则矩阵的最大值将为正数,但是如果我们要忽略符号,则以负号表示的数字也可以为最大值。如果我们想用其符号获得最大值,则可以在R中使用which.max函数。请查看以下示例以了解如何实现。
示例
M1<-matrix(sample(c(-1,5,-2,7,1),36,replace=TRUE),nrow=6) M1
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 7 5 1 -2 -1 1 [2,] -1 5 -1 -1 7 1 [3,] -2 5 7 1 -2 -2 [4,] 5 -1 5 -1 5 -2 [5,] -1 1 1 -1 -1 -1 [6,] 1 7 -2 1 5 -2
示例
M1[which.max(abs(M1))]
输出结果
[1] 7
示例
M2<-matrix(round(rnorm(100),0),nrow=10) M2
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0 -1 -1 -1 -1 -1 1 -1 1 0 [2,] 1 0 1 0 2 0 2 -1 0 0 [3,] 0 0 0 1 -1 -1 1 0 0 0 [4,] 1 1 -1 0 0 1 -1 2 -1 0 [5,] 1 -1 1 0 0 0 0 1 0 0 [6,] -1 0 1 2 0 -1 0 -1 2 0 [7,] 0 1 -2 -1 -1 0 0 2 0 0 [8,] 1 0 0 0 0 -1 1 0 0 1 [9,] 1 1 -1 -1 1 -3 0 0 2 -1 [10,] 0 0 0 -1 0 1 0 0 0 1
示例
M2[which.max(abs(M2))]
输出结果
[1] -3
示例
M3<-matrix(round(runif(25,-5,2),0),nrow=5) M3
输出结果
[,1] [,2] [,3] [,4] [,5] [1,] 1 1 -1 1 -1 [2,] -5 -3 -1 -4 0 [3,] 2 -3 -2 -2 1 [4,] -3 1 -2 -5 -2 [5,] -2 -2 0 -1 -1
示例
> M3[which.max(abs(M3))]
输出结果
[1] -5
示例
M4<-matrix(round(rnorm(100,1,0.98),0),nrow=10) M4
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 2 1 0 1 1 2 0 0 2 [2,] 1 1 2 3 1 2 2 0 0 1 [3,] 1 0 2 2 -1 1 1 0 1 0 [4,] 0 -1 0 0 0 1 -1 1 2 1 [5,] 0 3 -1 2 1 1 1 2 2 0 [6,] 2 2 1 -1 2 2 -1 -1 1 -1 [7,] 3 1 0 1 0 -1 0 2 -1 1 [8,] 1 2 1 1 0 -1 0 0 2 1 [9,] 2 -1 1 0 2 -1 2 0 1 3 [10,] 2 1 -1 3 0 2 1 0 0 2
示例
M4[which.max(abs(M4))] [1] 3
示例
M5<-matrix(round(rnorm(100,50,41),0),nrow=10) M5
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] -16 57 47 63 79 99 17 42 110 104 [2,] -4 55 51 -22 56 59 42 13 74 53 [3,] 2 53 96 84 94 74 86 90 79 18 [4,] -16 100 33 64 65 132 38 58 50 -8 [5,] 166 75 69 125 41 58 28 88 53 75 [6,] 26 3 25 -36 50 81 19 56 55 51 [7,] 55 -28 64 90 94 63 9 153 82 44 [8,] 100 76 63 48 31 66 65 96 106 111 [9,] 86 93 48 145 97 60 44 78 67 84 [10,] -19 82 0 119 68 28 43 65 24 6
示例
M5[which.max(abs(M5))]
输出结果
[1] 166
示例
M6<-matrix(sample(c(-10:10),64,replace=TRUE),nrow=8) M6
输出结果
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 9 5 -9 6 -1 6 -3 -2 [2,] 5 -1 -1 -10 -5 6 8 -7 [3,] 9 7 1 5 8 4 3 -7 [4,] -2 5 -2 6 0 -1 -9 2 [5,] 10 1 2 9 1 2 2 6 [6,] 8 -3 10 4 -4 2 -6 3 [7,] -1 3 0 8 4 -5 -9 -10 [8,] -9 -8 3 -6 -8 -6 6 -7
示例
M6[which.max(abs(M6))]
输出结果
[1] 10