查找矩阵中最大值的行和列索引 [英] Find row and column index of maximum value in a matrix

查看:438
本文介绍了查找矩阵中最大值的行和列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望找到矩阵的最大元素值及其位置(在矩阵的行和列ID中).

I wish to find the maximum element-value of a matrix and it's location (in row and column id in the matrix).

我正在使用以下函数返回矩阵的行和列.

I am using the following function to return the row and column of the matrix.

这似乎是一个糟糕的技巧-这是我可能缺少本机方法的一种情况.有更好的/更多R 方式吗?

This seems like a bad hack -- it's the sort of thing where i'm probably missing a native method. Is there a better / more R way?

这是我的职能:

matxMax <- function(mtx)
{
    colmn <- which(mtx == max(mtx)) %/% nrow(mtx) + 1
    row <- which(mtx == max(mtx)) %% nrow(mtx)
    return( matrix(c(row, colmn), 1))
}

我使用如下:

mm <- matrix(rnorm(100), 10, 10)
maxCords <- matxMax(mm)
mm[maxCords]

推荐答案

您可以做到

## Some data
set.seed(123)
mm <- matrix(rbinom(40, 20, 0.5), 8, 5)
mm
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    9   10    8   11   11
# [2,]   12   10    6   11   12
# [3,]    9   14    9   10    6
# [4,]   13   10   14   11   10
# [5,]   13   11   13    9   12
# [6,]    6   10   11    8    8
# [7,]   10    7   11   14    9
# [8,]   13   13   16   13    8

which(mm == max(mm), arr.ind = TRUE)
#      row col
# [1,]   8   3

这篇关于查找矩阵中最大值的行和列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆