Open In App

Dot Product of Vectors in R Programming

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In mathematics, dot product or commonly referred as the scalar product is an algebraic operation involving the two same-length sequences of numbers and a resultant single number. Let us assume two vectors A and B and we have to calculate the dot product of two vectors.

Formula for Dot Product

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

Example:

Given two vectors A and B as,
A = 3i + 5j + 4k and B = 2i + 7j + 5k

Dot Product = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 + 61 

Computing Dot Product in R

R provides efficient ways to calculate the dot product of two vectors. One common method is using the dot() function from the geometry package.

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

Example 1: Simple Dot Product of Scalars

In this example, let's calculate the dot product of two scalar values.

R
# Import the required library
library(geometry)

a = 5
b = 7

print(dot(a, b, d = TRUE))

Output:

[1] 35

Example 2: Dot Product of Complex Numbers

In this example, we use the Conj() function from the pracma package to calculate the dot product of two complex numbers.

R
install.packages("pracma")
library(pracma)

a <- 3 + 1i
b <- 7 + 6i

# Compute the dot product using the conjugate of b
dot_prod <- sum(a * Conj(b))
print(dot_prod)

Output:

[1] 27-11i

Explanation: The dot product of the complex numbers is computed using the conjugate of b.

Example 3: Dot Product of Two Vectors

R
library(geometry)

a = c(1, 4)
b = c(7, 4)

# Calculating dot product using dot()
print(dot(a, b, d = TRUE))

Output:

[1] 23

Explanation: The dot product of the vectors A = [1,4] and B = [7,4] is computed as (1â‹…7) +(4â‹…4) = 7 +16 = 23.

Example 4: Dot Product of 2D Arrays (Matrices)

In the following example let's consider two 2D arrays and find the dot product of these two. To initialize a 2D array in R please see Multidimensional Array in R.

R
# Import the required library
library(geometry)

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))

print(dot(a, b, d = TRUE))

Output:

[1] 10 9


Next Article

Similar Reads