Search code examples
pythonlistmatrixslicecut

How to cut a bigger matrix and match the shape of a smaller matrix


I have two lists of matrices with different lengths.

e.g.

length of matrices in X:

  • (110,3)
  • (150,3)
  • (120,3)

length of matrices in Y:

  • (100,3)
  • (125,3)

My problem is I have a loop that will subtract matrices e.g.(X[0]-Y[0]) and then (X[0]-Y[1]) and so on. Since they have different shapes, I have to create a code that will slice the matrix.

for x in range (len(X)):
   for y in range (len(Y)):
      if len(X[x])> len(Y[y]):
         X_a = len(X[x]) - len(Y[y])
         X_len = len(X[x]) - X_a

Am I going somewhere here? Sorry. This has been confusing for me. :(


Solution

  • From the code it seems that when you want to subtract two matrices you want to do the subtraction up to the length of the smaller matrix. To do that you can have a function like:

    def subtract_matricies(mat1, mat2):
        minimum_len = min(len(mat1), len(mat2))
        return mat1[:minimum_len]-mat2[:minimum_len]
    

    then in your main loop use this function:

    result=[]
    for x in X:
        for y in Y:
            result.append(subtract_matricies(x,y))