在保留+或 - 符号的同时找到最大绝对值

时间:2021-06-07 13:02:40

If I have a matrix:

如果我有一个矩阵:

mat=matrix(c(-21,14,28,17,-16,-9,-17,-30,18), nrow=3)
mat
          [,1]   [,2]  [,3]
     [1,]  -21     17    17
     [2,]   14    -16   -30
     [3,]   28     -9    18

I can isolate the highest absolute value simply with

我可以简单地用最高绝对值来隔离

max(abs(mat))

However how do I preserve the sign so I return -30? For some context, I have a large number of matrices and I need a command to isolate the highest absolute number in all of them including the sign (some will be positive others negative).

但是,如何保留标志,以便返回-30?对于某些上下文,我有大量的矩阵,我需要一个命令来隔离所有这些中的最高绝对数,包括符号(有些将是正数,其他是负数)。

Thanks in advance!

提前致谢!

2 个解决方案

#1


9  

You need the index of the value in the matrix which is the maximum absolute value, which you can then use to return the value itself. which.max will do this (and which.min for the opposite):

您需要矩阵中值的索引,该索引是最大绝对值,然后您可以使用该索引返回值本身。 which.max会这样做(以及相反的哪个.min):

mat[which.max( abs(mat) )]
# [1] -30

#2


6  

Building on Simon's answer. If you wanted a function that returned the absolute max for a vector or a matrix, you could use the following:

以西蒙的答案为基础。如果您想要一个返回向量或矩阵的绝对最大值的函数,您可以使用以下代码:

absmax <- function(x) { x[which.max( abs(x) )]}

E.g.,

> absmax(c(-10, 0, 9))
[1] -10

#1


9  

You need the index of the value in the matrix which is the maximum absolute value, which you can then use to return the value itself. which.max will do this (and which.min for the opposite):

您需要矩阵中值的索引,该索引是最大绝对值,然后您可以使用该索引返回值本身。 which.max会这样做(以及相反的哪个.min):

mat[which.max( abs(mat) )]
# [1] -30

#2


6  

Building on Simon's answer. If you wanted a function that returned the absolute max for a vector or a matrix, you could use the following:

以西蒙的答案为基础。如果您想要一个返回向量或矩阵的绝对最大值的函数,您可以使用以下代码:

absmax <- function(x) { x[which.max( abs(x) )]}

E.g.,

> absmax(c(-10, 0, 9))
[1] -10