R编程中向量的点积
在数学中,点积或也称为标量积是一种代数运算,它采用两个等长的数字序列并返回一个数字。让我们给出两个向量 A和B,我们必须找到两个向量的点积。
鉴于,
和,
where,
i: the unit vector along the x directions
j: the unit vector along the y directions
k: the unit vector along the z directions
然后点积计算为:
例子:
给定两个向量 A 和 B,
A = 3i + 5j + 4k,
and
B = 2i + 7j + 5k
Dot Product = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 + 61
在 R 中计算点积
R 语言提供了一种非常有效的方法来计算两个向量的点积。通过使用几何库中可用的dot()方法,可以做到这一点。
Syntax: dot(x, y, d = NULL)
Parameters:
x: Matrix of vectors
y: Matrix of vectors
d: Dimension along which to calculate the dot product
Return: Vector with length of dth dimension
示例 1:
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two scalar values
a = 5
b = 7
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two complex values
a = 3 + 1i
b = 7 + 6i
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two simple vectors
a = c(1, 4)
b = c(7, 4)
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two 2D array
vector1 = c(2, 1)
vector2 = c(0, 3)
a = array(c(vector1, vector2), dim = c(2, 2))
vector1 = c(4, 2)
vector2 = c(9, 3)
b = array(c(vector1, vector2), dim = c(2, 2))
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
输出:
[1] 35
示例 2:
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two complex values
a = 3 + 1i
b = 7 + 6i
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
输出:
[1] 15+25i
示例 3:
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two simple vectors
a = c(1, 4)
b = c(7, 4)
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
输出:
[1] 23
示例 4:
在以下示例中,让我们采用两个二维数组并计算这两个数组的点积。要在 R 中创建二维数组,请参阅 R 中的多维数组。
R
# R Program illustrating
# dot product of two vectors
# Import the required library
library(geometry)
# Taking two 2D array
vector1 = c(2, 1)
vector2 = c(0, 3)
a = array(c(vector1, vector2), dim = c(2, 2))
vector1 = c(4, 2)
vector2 = c(9, 3)
b = array(c(vector1, vector2), dim = c(2, 2))
# Calculating dot product using dot()
print(dot(a, b, d = TRUE))
输出:
[1] 10 9