📘
Matrix Multiplication and Element-wise Operations
MediumPyTorch Operations
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:
Matrix multiplication follows linear algebra rules, element-wise multiplies corresponding elements
Constraints:
- For matrix multiplication, dimensions must be compatible
- For element-wise multiplication, tensors must have same shape
- Input tensors contain integers
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.