在 R 中的矩阵中查找最大值和最小值的行和列索引
在本文中,我们将讨论如何在任何给定矩阵中找到最大值和最小值,并在 R 编程语言中打印其行和列索引。
例子:
Input: 11 -9 36
20 1 81
13 99 77
Output: maximum value: 99
row col
3 2
minimum value: -9
row col
1 2
寻找最大值:
- 在下面的代码中,我们创建了一个示例矩阵,其中我们在示例 1 中传递了“ nrow=3 ”(矩阵将只有 3 行)和在示例 2 中传递了“ ncol =2 ”(矩阵将只有 2 列) .
- 然后我们在下一行打印了带有“Sample Matrix”消息的样本矩阵。
- 然后我们使用下面的语法来找到最大元素的行号和列号,并将其存储在变量“max”中。我们使用了 max()函数,该函数用于查找对象中存在的最大元素。该对象可以是向量、列表、矩阵、数据框等。
- 该“()”函数是用来得到其满足给定的条件的值的索引或位置。然后我们打印了最大值及其行和列索引。
Syntax: which(m == max(m), arr.ind=TRUE)
示例 1:
R
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77),
nrow = 3)
print("Sample Matrix:")
print(m)
# stores indexes of max value
max = which(m == max(m), arr.ind = TRUE)
print(paste("Maximum value: ", m[max]))
print(max)
R
# defining a sample matrix
m = matrix(c(1:16), ncol = 2)
print("Sample Matrix:")
print(m)
# stores indexes of max value
max = which(m == max(m), arr.ind=TRUE)
print(paste("Maximum value: ",m[max]))
print(max)
R
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow = 3)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
R
# defining a sample matrix
m = matrix(c(1:16), ncol = 8)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
输出:
[1] "Sample Matrix:"
[,1] [,2] [,3]
[1,] 11 -9 36
[2,] 20 1 81
[3,] 13 99 77
[1] "Maximum value: 99"
row col
[1,] 3 2
示例 2:
电阻
# defining a sample matrix
m = matrix(c(1:16), ncol = 2)
print("Sample Matrix:")
print(m)
# stores indexes of max value
max = which(m == max(m), arr.ind=TRUE)
print(paste("Maximum value: ",m[max]))
print(max)
输出:
[1] "Sample Matrix:"
[,1] [,2]
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
[5,] 5 13
[6,] 6 14
[7,] 7 15
[8,] 8 16
[1] "Maximum value: 16"
row col
[1,] 8 2
寻找最小值:
- 在下面的代码中,我们创建了一个示例矩阵,其中我们在示例 1 中传递了“ nrow=3 ”(矩阵将只有 3 行)和在示例 2 中传递了“ ncol =8 ”(矩阵将只有 8 列)作为定义矩阵时的参数。
- 然后我们在下一行打印了带有“Sample Matrix”消息的样本矩阵。
- 然后我们使用下面的语法来找到最小元素的行号和列号,并将其存储在变量“min”中。我们使用了 min()函数,该函数用于查找对象中存在的最小元素。该对象可以是向量、列表、矩阵、数据框等。
- “which()”函数用于获取满足给定条件的值的索引或位置。然后我们打印了最小值及其行和列索引。
Syntax: which(m == min(m), arr.ind=TRUE)
示例 1:
电阻
# defining a sample matrix
m = matrix(c(11, 20, 13, -9, 1, 99, 36, 81, 77), nrow = 3)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
输出:
[1] "Sample Matrix:"
[,1] [,2] [,3]
[1,] 11 -9 36
[2,] 20 1 81
[3,] 13 99 77
[1] "Minimum value: -9"
row col
[1,] 1 2
示例 2:
电阻
# defining a sample matrix
m = matrix(c(1:16), ncol = 8)
print("Sample Matrix:")
print(m)
# stores indexes of min value
min = which(m == min(m), arr.ind = TRUE)
print(paste("Minimum value: ", m[min]))
print(min)
输出:
[1] "Sample Matrix:"
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 3 5 7 9 11 13 15
[2,] 2 4 6 8 10 12 14 16
[1] "Minimum value: 1"
row col
[1,] 1 1