PIXELBANKv9.1.0
Menu

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:

Input:
None
Output:
{'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}
Reasoning:
  • We create matrix M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] and compute its trace using torch.einsum('ii->', M), which contracts the indices to calculate the sum of the diagonal elements: 1+5+9=15.01+5+9 = 15.0.
  • The diagonal of matrix M is extracted using torch.einsum('ii->i', M), resulting in the list [1.0, 5.0, 9.0].
  • We compute the outer product of vectors a=[1,2,3] and b=[4,5] using torch.einsum('i,j->ij', a, b), which gives us the matrix [[1*4, 1*5], [2*4, 2*5], [3*4, 3*5]] = [[4.0, 5.0], [8.0, 10.0], [12.0, 15.0]].
  • The condition "trace_equals_diag_sum" is checked by comparing the computed trace (15.015.0) with the sum of the diagonal elements (1.0+5.0+9.0=15.01.0+5.0+9.0 = 15.0), resulting in True.

Constraints:

  • 'ii->' for trace
  • 'ii->i' for diagonal
  • 'i,j->ij' for outer product
🔒

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

0/0
Run code to see test results.
Trace and Diagonal with Einsum - Easy | PixelBank