Matrix Multiplication and Element-wise 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
a=[[1, 2], [3, 4]], b=[[5, 6], [7, 8]]
{"matmul": [[19, 22], [43, 50]], "elementwise": [[5, 12], [21, 32]]}- Inputs:
aandbare integer matrices, and . - Matrix product: entry is row of dotted with column of , . Row 1: , . Row 2: , . That gives
[[19, 22], [43, 50]]undermatmul. - Element-wise product: each entry is just , with no summing: , giving
[[5, 12], [21, 32]]underelementwise. - Output: both results are integer matrices, since integer products and sums stay integers.
- Notice the shape rules differ: an matrix times an matrix gives , while the element-wise product needs identical shapes. Swapping and 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