📌  相关文章
📜  在 R 中的矩阵中查找非零元素的索引

📅  最后修改于: 2022-05-13 01:55:43.528000             🧑  作者: Mango

在 R 中的矩阵中查找非零元素的索引

在本文中,我们将讨论如何在 R 编程语言中找到矩阵中非零元素的索引。

方法一:使用for循环

可以在行和列上执行 for 循环迭代以访问矩阵中包含的单元格值。检查每个元素的非零值,如果满足约束,则显示相应的单元格索引。所需的时间复杂度相当于 O(n * m),其中 n 是行数,m 是列数。

R
# declaring a matrix in R
mat <- matrix(c(-1, 2, 0, 6, 0, 4), nrow = 2)
print ("Original Matrix")
print (mat)
print ("Indices of non-zero elements")
  
# computing indexes of non 
# zero elements looping through 
# rows
for (i in 1:nrow(mat)){
  
    # looping through columns
    for(j in 1:ncol(mat)){
      
        # check if element is non 
          # zero
        if(mat[i,j]!=0){
          
            # display the row and column
              # index
            cat(i, j,"\n")             
        }
    }
}


R
# declaring a matrix in R
mat <- matrix(c(-1, 2, 0, 6, 0, 4), nrow = 2)
print ("Original Matrix")
print (mat)
print ("Indices of non-zero elements")
  
# computing indexes of non zero 
# elements
which(mat != 0, arr.ind = T)


R
# declaring a matrix in R
mat <- matrix(letters[1:8], nrow = 2)
print ("Original Matrix")
print (mat)
print ("Indices of non-zero elements")
  
# computing indexes of non zero 
# elements
which(mat != 0, arr.ind = T)


输出



[1] "Original Matrix"
    [,1] [,2] [,3]
[1,]   -1    0    0
[2,]    2    6    4
[1] "Indices of non-zero elements"
1 1
2 1
2 2
2 3 

方法二:使用which()方法

which() 方法用于返回满足给定约束的值的位置或索引。它对指定的 R 对象、向量或数据框或矩阵的每个元素应用条件,然后返回满足值的相应单元格位置。在此方法中,缺失值或 NA 被视为 FALSE。

如果 arr.ind 参数设置为 FALSE,则返回单元格值而不是索引。返回的索引以表格的形式显示,其中 row 和 col 作为各列的标题。

电阻

# declaring a matrix in R
mat <- matrix(c(-1, 2, 0, 6, 0, 4), nrow = 2)
print ("Original Matrix")
print (mat)
print ("Indices of non-zero elements")
  
# computing indexes of non zero 
# elements
which(mat != 0, arr.ind = T)

输出:

[1] "Original Matrix"
    [,1] [,2] [,3]
[1,]   -1    0    0
[2,]    2    6    4
[1] "Indices of non-zero elements"
    row col
[1,]   1   1
[2,]   2   1
[3,]   2   2
[4,]   2   3

该方法也适用于字符数组或矩阵。在这种情况下,整个矩阵单元格的位置作为输出返回。

电阻

# declaring a matrix in R
mat <- matrix(letters[1:8], nrow = 2)
print ("Original Matrix")
print (mat)
print ("Indices of non-zero elements")
  
# computing indexes of non zero 
# elements
which(mat != 0, arr.ind = T)

输出

[1] "Original Matrix"
    [,1] [,2] [,3] [,4]
[1,] "a"  "c"  "e"  "g"
[2,] "b"  "d"  "f"  "h"
[1] "Indices of non-zero elements"
    row col
[1,]   1   1
[2,]   2   1
[3,]   1   2
[4,]   2   2
[5,]   1   3
[6,]   2   3
[7,]   1   4
[8,]   2   4