如何修复:R中矩阵上的下标数量不正确
在编程中出错是很常见的,当我们的源代码变得更庞大时,它们的频率会增加。在本文中,我们将讨论如何解决:R 中矩阵上不正确的下标数量。
这个错误在第一次出现时并没有给我们任何线索。由于一个非常小的错误,可能会发生此错误。对于程序员来说,这个错误可能很容易犯,但是对于大多数程序员来说,发现这个错误有时会变得很困难。
什么时候可能出现这个错误?
当程序员尝试在本身不是矩阵的数据结构上使用矩阵表示法时,可能会发生这些错误。这种类型的错误是一种正常的错误,但有时如果您对所使用的数据结构没有任何明确性,可能很难找到。
例子:
R
# R program to illustrate when this
# error might occur
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
for(i in 1:5)
{
# Assigning at all columns of the
# ith row
vect[i,] = 10
}
R
# R program to illustrate reasons for the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
for(i in 1:5)
{
# Assigning at all columns of the ith row
vect[i,] = 10
}
R
# R program to fix the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
# Note that we have removed the comma (,)
# Since we are dealing with 1-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at the ith index of the vect
vect[i] = 10
}
R
# R program to fix the error
# Creating a 2-dimensional data structure (matrix)
# mat has 5 rows and 5 columns
mat = matrix(rep(0,5), nrow=5, ncol=5)
# Assign values in the created matrix
# Note that we have added the comma (,)
# Since we are dealing with 2-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at all columns of the ith row
mat[i,] = 10
}
# Print the matrix
print(mat)
输出:
为什么会出现这个错误?
当程序员试图将矩阵表示法应用于向量时,会发生这种类型的错误。
例子:
在下面的源代码中,我们创建了一个向量 vect(一维数据结构)。使用 for 循环,我们从 i = 1 迭代到 i = 100,并且在迭代的每一步,我们将值 10 分配给第i行的所有列。但是 vect 是一维数据结构,我们在其上应用矩阵表示法。因此,下面的源代码将导致错误:“矩阵上的下标数量不正确”,如输出中所见。
R
# R program to illustrate reasons for the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
for(i in 1:5)
{
# Assigning at all columns of the ith row
vect[i,] = 10
}
如何修复此错误?
修复此错误基于下面讨论的两种不同的意识形态。
思想1:当我们要处理一维数据结构时。
当我们确定要处理一维数据结构(如向量)时,我们可以像下面的示例一样修复此错误。
例子:
R
# R program to fix the error
# Creating a vector
vect = rep(1, 5)
# Assign values in the created vector
# Note that we have removed the comma (,)
# Since we are dealing with 1-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at the ith index of the vect
vect[i] = 10
}
输出:
意识形态2:当我们要处理二维数据结构时。
当我们确定要处理二维数据结构(如矩阵)时,我们可以像下面的示例一样修复此错误。
例子:
R
# R program to fix the error
# Creating a 2-dimensional data structure (matrix)
# mat has 5 rows and 5 columns
mat = matrix(rep(0,5), nrow=5, ncol=5)
# Assign values in the created matrix
# Note that we have added the comma (,)
# Since we are dealing with 2-dimensional
# data structure
for(i in 1:5)
{
# Assigning 10 as the value
# at all columns of the ith row
mat[i,] = 10
}
# Print the matrix
print(mat)
输出: