You can download this code by clicking the button below.
This code is now available for download.
This function takes a 2D tensor and a number of rows as input. It first checks the validity of the input, then transposes the matrix, and returns a new matrix where the transposed part is the top num_rows rows of the original matrix.
Technology Stack : PyTorch, NumPy
Code Type : Function
Code Difficulty : Intermediate
import torch
import numpy as np
def random_matrix_transpose(matrix, num_rows):
"""
This function takes a 2D tensor and transposes it by a specified number of rows.
"""
if not isinstance(matrix, torch.Tensor):
raise TypeError("Input matrix must be a torch.Tensor")
if not isinstance(num_rows, int) or num_rows <= 0:
raise ValueError("Number of rows must be a positive integer")
# Transpose the matrix
transposed_matrix = matrix.transpose(0, 1)
# Slice the first num_rows to get the top left block
top_left_block = transposed_matrix[:num_rows, :]
# Slice the rest to get the bottom right block
bottom_right_block = transposed_matrix[num_rows:, :]
# Concatenate the top left block with the original bottom right block
result_matrix = torch.cat((top_left_block, bottom_right_block), dim=0)
return result_matrix