Trace and Diagonal with Einsum
Problem Statement
Use einsum to compute the trace, extract the diagonal, and compute an outer product.
Background
Repeated indices on the same tensor access diagonal elements. Summing repeated indices gives the trace, keeping them gives the diagonal. Two separate indices create an outer product.
Your Task
The starter code creates a matrix M and vectors a, b. Use einsum to compute three operations: the trace of M, the diagonal of M, and the outer product of a and b.
Output Format
Returns a dictionary with "trace", "diagonal", "outer_product", and "trace_equals_diag_sum".
Example
None
{'trace': 15.0, 'diagonal': [1.0, 5.0, 9.0], 'outer_product': [[4.0, 5.0], [8.0, 10.0], [12.0, 15.0]], 'trace_equals_diag_sum': True}- Inputs: a matrix with rows , , , and two vectors of length 3 and of length 2. All values are floats, hence the
.0endings. - Trace: the diagonal entries share one index for row and column. Summing over gives a scalar: , giving
15.0. - Diagonal: the same entries, but with kept rather than summed away, so the result is a length-3 vector:
[1.0, 5.0, 9.0]. - Outer product: two different indices give every pairing, . With 3 values of and 2 of the result is : row 1 is , row 2 is , row 3 is .
- Check: matches the trace, so
trace_equals_diag_sumisTrue. Notice that trace and diagonal differ only in whether the repeated index survives.
Constraints
- 'ii->' for trace
- 'ii->i' for diagonal
- 'i,j->ij' for outer product