R语言 提取矩阵主对角线以上的数值
在这篇文章中,我们将了解如何在R编程语言中提取矩阵主对角线上方的数值。
矩阵的主对角线是连接矩阵中行和列相同的条目(或元素)的一条直线。主对角线上的元素数量等同于矩阵中的行数或列数。在矩阵A中,对于矩阵的每一行 i ,和每一列 j ,矩阵的对角线元素由以下内容给出。
Aij where i=j
例子:
输入矩阵:
[[3, 1, 9],
[8, 2, 3],
[7, 11, 4]]
输出 : 1, 9, 3
解释 :在上述矩阵中,主对角线是[3, 2, 4] 。
我们必须提取主对角线元素以上的数值。
因此,答案将是1, 9, 3。
创建简单的矩阵
矩阵可以用matrix()方法创建,该方法用于将指定的数据元素排列到指定的行和列数中。该方法的语法如下。
语法 : matrix (data, nrow = rows, ncol = cols)
参数:
- data – 要排列到矩阵中的数据。
- rows – 矩阵中的行数。
- cols – 矩阵中的列数。
# declaring the number of rows
nrow <- 4
# declaring the number of columns
ncol <- 4
# creating matrix
mat <- matrix(1:16, nrow = nrow,
ncol = ncol)
# printing the matrix
print ("Matrix : ")
print(mat)
输出
[1] "Matrix : "
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
提取矩阵中主对角线的上述数值
可以用一个嵌套的for循环来迭代矩阵的行和列。一个外循环用来迭代行元素,一个内循环用来迭代列元素。如果条件是用来检查列号是否大于行号的。然后从矩阵中提取该元素。
# declaring the number of rows
nrow <- 4
# declaring the number of columns
ncol <- 4
# creating matrix
mat <- matrix(1:16, nrow = nrow,
ncol = ncol)
# printing the matrix
print ("Matrix : ")
print(mat)
# getting the elements above
# the main diagonal elements
# looping over rows
for(row in 1:nrow(mat))
{
# looping over columns
for(col in 1:ncol(mat))
{
# if column number is greater than row
if(col > row)
{
# printing the element of the matrix
print(mat[row,col])
}
}
}
输出
[1] "Matrix : "
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
A
[1] 5
[1] 9
[1] 13
[1] 10
[1] 14
[1] 15