v9.1.1
Menu

Dot Product

easyFREELinear Algebra BasicsNumPy Linear AlgebraNumPy Foundations

Problem Statement

Compute dot products and matrix multiplications.

Background

NumPy provides several multiplication operations:

  • np.dot(a, b) - dot product
  • a @ b - matrix multiplication (Python 3.5+)
  • a * b - element-wise multiplication

For vectors: dot product = sum of element-wise products For matrices: standard matrix multiplication

Your Task

Write a function compute_products(vec1, vec2, mat) that computes various products.

Output Format

Return a dictionary with:

  • "dot": Dot product of vec1 and vec2 (a plain Python int)
  • "elementwise": Element-wise product of vec1 and vec2 (a plain Python list)
  • "mat_vec": Matrix times vec1 (a plain Python list)
  • "vec_mat": vec1 times matrix (a plain Python list)

The dictionary is printed, so values must be built-in Python types, not NumPy scalars or arrays.

Example

Input
vec1 = [1,2,3], vec2 = [4,5,6], mat = identity
Output
{'dot': 32, 'elementwise': [4, 10, 18], 'mat_vec': [1, 2, 3], 'vec_mat': [1, 2, 3]}
Reasoning
  • Inputs: vec1 =(1,2,3)= (1, 2, 3) and vec2 =(4,5,6)= (4, 5, 6) are length-3 vectors; mat is the 3×33 \times 3 identity matrix II (ones on the diagonal, zeros elsewhere).
  • dot: multiply matching entries and add them up: 1⋅4+2⋅5+3⋅6=4+10+18=321 \cdot 4 + 2 \cdot 5 + 3 \cdot 6 = 4 + 10 + 18 = 32.
  • elementwise: keep the matching products separately instead of adding them: (4,10,18)(4, 10, 18). Notice that its entries sum to the dot product, 3232.
  • mat_vec: entry ii is ∑jmijvj\sum_j m_{ij} v_j, the dot product of row ii of the matrix with vec1. With II, row ii picks out viv_i alone, giving (1,2,3)(1, 2, 3).
  • vec_mat: entry jj is ∑ivimij\sum_i v_i m_{ij}, the dot product of vec1 with column jj. II again gives (1,2,3)(1, 2, 3).
  • Notice: the last two only agree here because II is symmetric. For M=(1234)M = \begin{pmatrix}1 & 2\\3 & 4\end{pmatrix} and v=(1,1)v = (1, 1), Mv=(3,7)Mv = (3, 7) but vM=(4,6)vM = (4, 6).

Constraints

  • vec1 and vec2 have same length
  • mat is square with size matching vector length

Learn this in

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.