In: Computer Science
I am trying to write a python code to create a function that returns all possible dimensions (reshaping) for an input matrix, can someone explains the math and write a python code with explaining all the steps and give me a test cases, and please explain if there is more than one approach. so if we have 1*8 matrix we should return 1*8, 2*4,4*2,8*1
def reshaping(M) should return a n ORDERED list AND the all possible reshaped matrices
import numpy as np #for using reshape() function to reshape matrix with each dimension
def reshaping(M): #function definition
m = len(M) #calculating number of rows
n = len(M[0]) #calculating number of columns
elements = m*n #calculating number of elements in the matrix
'''so the main maths behind this is that all the factors of total elements in matrix
will have a reshape possible starting from 1 to total elements
so here we will loop all such factors and create a dimension from it
after that we will reshape matrix for each dimension we added to the list'''
dimensions = [] #to store all the dimensions possible for a matrix
reshaped_matrices = [] #to store all the reshaped matrices
for i in range(1, elements+1):
if elements%i == 0: #factor will completely divide total elements
dimensions.append(f'{i}*{elements // i}') #appending dimension to the list
reshaped_matrices.append(M.reshape(i, elements//i)) #reshaping and appending
return dimensions, reshaped_matrices #returning the dimension list and reshaped matrices
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) #testcase 1
M = arr.reshape(4,3) #creating a sample matrix
dim, res = reshaping(M) #calling the function
print(f'Ordered List of all possible dimensions: {dim}\n') #printing ordered dimension list
for i in res: #printing each reshaped matrix
print(i, '\n')
Screenshot of output: