如何识别数组中最大值的位置?

编程入门 行业动态 更新时间:2024-10-10 23:25:22
本文介绍了如何识别数组中最大值的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的数组是

x <- array(1:24, dim=c(3,4,3))

我的任务1是根据前两个维度找到最大值

My task 1 is to find the max value according to the first two dimensions

x.max <- apply(x,c(1,2), function(x) ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE)))

如果有NA数据 我的任务2是在第三维上找到最大值位置. 我尝试过

in case there is NA data my task 2 is to find the max value position on the third dimension. I tried

x.max.position = apply(x, c(1,2),which.max(x))

但这只给了我在拳头两个维度上的位置.

But this only give me the position on the fist two dimensions.

有人可以帮助我吗?

推荐答案

目前尚不完全清楚,但是如果您要为每个三维维度的矩阵找到max(那是技术上正确的说法吗? ),那么您需要在第三维中使用apply. ?apply下的参数margin指出:

It's not totally clear, but if you want to find the max for each matrix of the third dimension (is that even a technically right thing to say?), then you need to use apply across the third dimension. The argument margin under ?apply states that:

一个给出下标的向量,该函数将被应用到下标.例如,对于矩阵,1表示行,2表示列,c(1,2)表示行和列.

a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.

因此,对于具有3D数组的示例,3是第三维.所以...

So for this example where you have a 3D array, 3 is the third dimension. So...

t( apply( x , 3 , function(x) which( x == max(x) , arr.ind = TRUE ) ) ) [,1] [,2] [1,] 3 4 [2,] 3 4 [3,] 3 4

这将返回一个矩阵,其中每行包含第三个维度的每个2D数组/矩阵的最大值的行和列索引.

Which returns a matrix where each row contains the row and then column index of the max value of each 2D array/matrix of the third dimension.

如果希望在所有维度上使用max,则可以使用which和arr.ind参数,如下所示:

If you want the max across all dimensions you can use which and the arr.ind argument like this:

which( x==max(x,na.rm=T) , arr.ind = T ) dim1 dim2 dim3 [1,] 3 4 2

告诉我们max的值是第三行,第四列,第二个矩阵.

Which tells us the max value is the third row, fourth column, second matrix.

要找到第3点的位置,第1点和第2点的值最大,请尝试:

To find the position at dim 3 where where values on dim 1 and 2 are max try:

which.max( apply( x , 3 , max ) ) # [1] 2

告诉我们,三维的第2个位置包含最大值.

Which tells us that at position 2 of the third dimension contains the maximal value.

更多推荐

如何识别数组中最大值的位置?

本文发布于:2023-11-29 08:55:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645929.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最大值   组中   如何识别   位置

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!