R编程中向量的叉积
在数学中,叉积或也称为向量积是在三维空间中对两个向量进行的二元运算,用符号“ X ”表示。给定两个线性独立的向量 a 和 b,叉积, a × b是一个垂直于 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
然后叉积计算为:
where,
are the coefficient of unit vector along i, j and k directions.
例子:
给定两个向量 A 和 B,
A = 3i + 5j + 4k,
and
B = 2i + 7j + 5k
Cross Product = (5 ? 5 – 4 ? 7)i + (4 ? 2 – 3 ? 5)j + (3 ? 7 – 5 ? 2)k
= (?3)i + (?7)j + (11)k
在 R 中计算叉积
R 语言提供了一种非常有效的方法来计算两个向量的叉积。通过使用pracma库中可用的cross()方法。此函数计算 3 维向量的叉积或向量积。在矩阵的情况下,它采用长度为 3 的第一个维度并计算相应列或行之间的叉积。
Syntax: cross(x, y)
Parameters:
x: numeric vector or matrix
y: numeric vector or matrix
# 将输入作为向量
示例 1:
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two vectors
a = c(3, 5, 4)
b = c(2, 7, 5)
# Calculating cross product using cross()
print(cross(a, b))
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two vectors
a = c(23, 15, 49)
b = c(28, 17, 25)
# Calculating cross product using cross()
print(cross(a, b))
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two matrices
a = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
b = matrix(
c(5, 2, 1, 4, 6, 6, 3, 2, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
# Calculating cross product using cross()
print(cross(a, b))
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two matrices
a = matrix(
c(11, 2, 31, 4, 52, 64, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
b = matrix(
c(85, 21, 1, 4, 61, 6, 32, 2, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
# Calculating cross product using cross()
print(cross(a, b))
输出:
[1] -3 -7 11
示例 2:
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two vectors
a = c(23, 15, 49)
b = c(28, 17, 25)
# Calculating cross product using cross()
print(cross(a, b))
输出:
[1] -458 797 -29
# 以输入为矩阵
示例 1:
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two matrices
a = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
b = matrix(
c(5, 2, 1, 4, 6, 6, 3, 2, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
# Calculating cross product using cross()
print(cross(a, b))
输出:
[, 1] [, 2] [, 3]
[1, ] -4 14 -8
[2, ] -6 0 4
[3, ] 54 -36 -10
示例 2:
R
# R Program illustrating
# cross product of two vectors
# Import the required library
library(pracma)
# Taking two matrices
a = matrix(
c(11, 2, 31, 4, 52, 64, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
b = matrix(
c(85, 21, 1, 4, 61, 6, 32, 2, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
# Calculating cross product using cross()
print(cross(a, b))
输出:
[, 1] [, 2] [, 3]
[1, ] -649 2624 61
[2, ] -3592 232 36
[3, ] 54 225 -242