📜  R编程中向量的点积

📅  最后修改于: 2022-05-13 01:55:47.315000             🧑  作者: Mango

R编程中向量的点积

在数学中,点积或也称为标量积是一种代数运算,它采用两个等长的数字序列并返回一个数字。我们给出两个向量 AB,我们必须找到两个向量的点积。

鉴于,

A = a_1i + a_2j + a_3k

和,

B = b_1i + b_2j + b_3k

然后点积计算为:

DotProduct = a_1 * b_1 + a_2 * b_2 + a_3 * b_3

例子:

给定两个向量 A 和 B,

在 R 中计算点积

R 语言提供了一种非常有效的方法来计算两个向量的点积。通过使用几何库中可用的dot()方法,可以做到这一点。

示例 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