矩阵是元素布置成二维矩形布局的R对象。 它们包含相同原子类型的元素。尽管我们可以创建只包含字符或只逻辑值的矩阵,但是它们没有多大用处。我们使用的是在数学计算中含有数字元素矩阵。
使用 matrix()函数创建一个矩阵。
语法
R语言中创建矩阵的基本语法是:
matrix(data, nrow, ncol, byrow, dimnames)
以下是所使用的参数的说明:
data- 是这成为矩阵的数据元素输入向量。
nrow - 是要创建的行数。
ncol - 要被创建的列的数目。
byrow - 是一个合乎逻辑。如果为True,那么输入向量元素在安排的行。
dimname - 是分配给行和列名称。
示例
创建矩阵取向量的数量作为输入
# Elements are arranged sequentially by row.
M
print(M)
# Elements are arranged sequentially by column.
N
print(N)
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P
print(P)
当我们上面的代码执行时,它产生以下结果:
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
访问矩阵的元素
矩阵的元素可以通过使用元素的列和行索引来访问。我们考虑矩阵P上面找到具体内容如下。
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
# Create the matrix.
P
# Access the element at 3rd column and 1st row.
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4,2])
# Access only the 2nd row.
print(P[2,])
# Access only the 3rd column.
print(P[,3])
当我们上面的代码执行时,它产生以下结果:
[1] 5
[1] 13
col1 col2 col3
6 7 8
row1 row2 row3 row4
5 8 11 14
矩阵计算
各种数学操作是在使用R运算矩阵执行。该操作的结果也是一个矩阵。
大小(行和列的数目)应与参与操作的矩阵相同。
矩阵加法和减法
# Create two 2x3 matrices.
matrix1
print(matrix1)
matrix2
print(matrix2)
# Add the matrices.
result
cat("Result of addition","\n")
print(result)
# Subtract the matrices
result
cat("Result of subtraction","\n")
print(result)
当我们上面的代码执行时,它产生以下结果:
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of addition
[,1] [,2] [,3]
[1,] 8 -1 5
[2,] 11 13 10
Result of subtraction
[,1] [,2] [,3]
[1,] -2 -1 -1
[2,] 7 -5 2
矩阵乘法和除法
# Create two 2x3 matrices.
matrix1
print(matrix1)
matrix2
print(matrix2)
# Multiply the matrices.
result
cat("Result of multiplication","\n")
print(result)
# Divide the matrices
result
cat("Result of division","\n")
print(result)
当我们上面的代码执行时,它产生以下结果:
[,1] [,2] [,3]
[1,] 3 -1 2
[2,] 9 4 6
[,1] [,2] [,3]
[1,] 5 0 3
[2,] 2 9 4
Result of multiplication
[,1] [,2] [,3]
[1,] 15 0 6
[2,] 18 36 24
Result of division
[,1] [,2] [,3]
[1,] 0.6 -Inf 0.6666667
[2,] 4.5 0.4444444 1.5000000
来源:https://www.cnblogs.com/csguo/p/7291242.html