R中的元素矩阵乘法
在矩阵中,我们知道行是水平运行的,列是垂直运行的。在本文中,我们将在 R 编程中执行逐元素矩阵乘法。
方法
- 创建矩阵
- 两个矩阵相乘
- 验证结果。
使用“*”运算符的逐元素乘法:
Syntax: matrix1*matrix*2…..matrix n
示例 1:
此代码显示了两个矩阵 data1 和 data2 的元素乘法,Data 包含 5 行和 2 列:
R
# Creating matrices 10 elements each using
# range operator ":"
data1 <- matrix(1:10, nrow = 5)
print(data1)
data2 <- matrix(11:20, nrow = 5)
print(data2)
# perform element wise multiplication
print(data1*data2)
R
# Creating matrices 10 elements each
# using range operator ":"
data1 <- matrix(1:10, nrow = 5)
print(data1)
data2 <- matrix(11:20, nrow = 5)
print(data2)
data3 <- matrix(21:30, nrow = 5)
# perform element wise multiplication
print(data1*data2*data3)
R
# vector a
a = c(3, 4, 5, 6, 7, 8)
# vector b
b=c(1, 3, 0, 7, 8, 5)
# Creating matrices using vector
data1 <- matrix(a, nrow = 3)
print(data1)
data2 <- matrix(b, nrow = 3)
print(data2)
print(data1*data2)
R
# vector a
a = c(3, 4, 5, 6, 7, 8)
# vector b
b = c(1, 3, 0, 7, 8, 5)
# Creating matrices using vector
data1 <- matrix(a, ncol = 3)
print(data1)
data2 <- matrix(b, ncol = 3)
print(data2)
print(data1*data2)
输出:
示例 2:
此代码用于多个矩阵 data1、data2、data3 的乘法。所有数据都包含使用范围运算符创建的 5 行。
电阻
# Creating matrices 10 elements each
# using range operator ":"
data1 <- matrix(1:10, nrow = 5)
print(data1)
data2 <- matrix(11:20, nrow = 5)
print(data2)
data3 <- matrix(21:30, nrow = 5)
# perform element wise multiplication
print(data1*data2*data3)
输出:
示例 3:
此代码显示矩阵是使用向量创建的。并完成矩阵乘法。
电阻
# vector a
a = c(3, 4, 5, 6, 7, 8)
# vector b
b=c(1, 3, 0, 7, 8, 5)
# Creating matrices using vector
data1 <- matrix(a, nrow = 3)
print(data1)
data2 <- matrix(b, nrow = 3)
print(data2)
print(data1*data2)
输出:
示例 4:
显示乘法列排列和矩阵 data1 和 data2 并相乘的示例。列方面,我们将执行矩阵乘法 data1 和 data2 包含 3 列,元素是使用向量创建的。
电阻
# vector a
a = c(3, 4, 5, 6, 7, 8)
# vector b
b = c(1, 3, 0, 7, 8, 5)
# Creating matrices using vector
data1 <- matrix(a, ncol = 3)
print(data1)
data2 <- matrix(b, ncol = 3)
print(data2)
print(data1*data2)
输出: