v9.1.1
Menu

Matrix Multiplication and Element-wise Operations

mediumPROBasic OpsPyTorch OperationsPytorch

Problem Statement

Implement functions to perform both matrix multiplication and element-wise multiplication on tensors.

Background

PyTorch supports two types of multiplication that behave very differently:

  • Matrix multiplication: follows linear algebra rules (dot products of rows and columns)
  • Element-wise multiplication: multiplies corresponding elements directly

Understanding the difference is crucial for neural network operations.

Your Task

Write two functions:

  • matrix_multiply(a, b) — returns the matrix product of two tensors
  • elementwise_multiply(a, b) — returns the element-wise product of two tensors

Output Format

Each function should return a tensor.

Example

Input
a=[[1, 2], [3, 4]], b=[[5, 6], [7, 8]]
Output
{"matmul": [[19, 22], [43, 50]], "elementwise": [[5, 12], [21, 32]]}
Reasoning
  • Inputs: a and b are 2×22 \times 2 integer matrices, a=(1234)a = \begin{pmatrix}1 & 2\\3 & 4\end{pmatrix} and b=(5678)b = \begin{pmatrix}5 & 6\\7 & 8\end{pmatrix}.
  • Matrix product: entry (i,j)(i, j) is row ii of aa dotted with column jj of bb, cij=∑kaikbkjc_{ij} = \sum_k a_{ik} b_{kj}. Row 1: 1⋅5+2⋅7=191 \cdot 5 + 2 \cdot 7 = 19, 1⋅6+2⋅8=221 \cdot 6 + 2 \cdot 8 = 22. Row 2: 3⋅5+4⋅7=433 \cdot 5 + 4 \cdot 7 = 43, 3⋅6+4⋅8=503 \cdot 6 + 4 \cdot 8 = 50. That gives [[19, 22], [43, 50]] under matmul.
  • Element-wise product: each entry is just aij⋅bija_{ij} \cdot b_{ij}, with no summing: 5,12,21,325, 12, 21, 32, giving [[5, 12], [21, 32]] under elementwise.
  • Output: both results are 2×22 \times 2 integer matrices, since integer products and sums stay integers.
  • Notice the shape rules differ: an m×nm \times n matrix times an n×pn \times p matrix gives m×pm \times p, while the element-wise product needs identical shapes. Swapping aa and bb changes the matrix product but not the element-wise one.

Constraints

  • For matrix multiplication, dimensions must be compatible
  • For element-wise multiplication, tensors must have same shape
  • Input tensors contain integers

Learn this in

More from Pytorch

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.