v9.1.1
Menu

Tensor Slicing and Indexing

mediumPROBasic OpsPyTorch OperationsPytorch

Problem Statement

Given a 2D tensor, extract specific rows, columns, and sub-matrices using PyTorch indexing.

Background

PyTorch tensors support NumPy-style indexing and slicing, allowing you to extract arbitrary parts of a tensor.

Your Task

Write a function extract_parts(tensor) that takes a 4×4 tensor and returns a dictionary with its first row, last column, and center 2×2 sub-matrix.

Output Format

Return a dictionary with keys: "first_row", "last_column", "center".

Each value must be a PyTorch tensor (first_row and last_column have 4 elements, center is 2×2). The sample below shows them as lists for readability.

Example

Input
torch.arange(16).reshape(4, 4)
Output
{"first_row": [0, 1, 2, 3], "last_column": [3, 7, 11, 15], "center": [[5, 6], [9, 10]]}
Reasoning
  • Input: a 4×44 \times 4 integer tensor. In the sample its entries are 00 to 1515 laid out row by row, so the entry in row ii, column jj (counting from 00) is tij=4i+jt_{ij} = 4i + j.
  • first_row: fix i=0i = 0 and let jj run from 00 to 33: t00,t01,t02,t03=0,1,2,3t_{00}, t_{01}, t_{02}, t_{03} = 0, 1, 2, 3. A 1-D tensor of length 4.
  • last_column: fix j=3j = 3 and let ii run from 00 to 33: 4i+34i + 3 gives 3,7,11,153, 7, 11, 15. Each row down adds 4. Notice it comes back as a flat length-4 vector, not a 4×14 \times 1 column.
  • center: drop the outer ring and keep rows {1,2}\{1, 2\} crossed with columns {1,2}\{1, 2\}: t11=5t_{11} = 5, t12=6t_{12} = 6, t21=9t_{21} = 9, t22=10t_{22} = 10, giving [[5, 6], [9, 10]]. This part stays 2-D.
  • Output: a dictionary mapping the three keys to tensors (shown as lists for display). An all-ones input gives all-ones parts with the same shapes.

Constraints

  • Input tensor is always 4x4
  • Values are integers
  • Return a dictionary with the three required keys

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.