R语言 创建两个2×3的矩阵并进行加、减、乘、除运算
在这篇文章中,我们将创建两个各有2行和3列的矩阵,然后在R编程语言中对这两个矩阵进行加、减、乘、除。
我们可以通过使用nrow和ncol参数在矩阵中创建行和列,nrow指定行的数量,ncol指定矩阵中的列的数量。
语法: matrix(data,nrow,ncol)
**Sample Input:**
[,1] [,2] [,3]
[1,] 3 5 3
[2,] 4 2 4
[,1] [,2] [,3]
[1,] 3 2 8
[2,] 4 7 9
**Sample Output:**
"Addition"
[,1] [,2] [,3]
[1,] 6 7 11
[2,] 8 9 13
"Subtraction"
[,1] [,2] [,3]
[1,] 0 3 -5
[2,] 0 -5 -5
"Multiplication"
[,1] [,2] [,3]
[1,] 9 10 24
[2,] 16 14 36
"Division"
[,1] [,2] [,3]
[1,] 1 2.5000000 0.3750000
[2,] 1 0.2857143 0.4444444
例子
R程序创建两个各有2行和2列的矩阵并显示。
# create first matrix
first = matrix(c(3,4,5,2,3,4), nrow = 2,ncol=3)
# create second matrix
second = matrix(c(3,4,2,7,8,9), nrow = 2,ncol=3)
# display
print(first)
print(second)
输出
我们可以用+运算符做加法,用-运算符做减法,用/运算符做除法,用*
运算符做乘法。在第一个矩阵的行/列中的每个数字与第二个元素中的其他元素在同一位置上进行运算。
例子
在这个例子中,我们要对上述矩阵进行上述操作。
# create first matrix
first = matrix(c(3,4,5,2,3,4), nrow = 2,ncol=3)
# create second matrix
second = matrix(c(3,4,2,7,8,9), nrow = 2,ncol=3)
print("Addition")
# add 2 matrices
print(first+second)
print("Subtraction")
# subtract2 matrices
print(first-second)
print("Multiplication")
# multiply 2 matrices
print(first*second)
print("Division")
# divide 2 matrices
print(first/second)
输出