Matrix flip horizontal or vertical

15,323

Solution 1

Try this:

import numpy as np
def matrixflip(m,d):
    myl = np.array(m)
    if d=='v': 
        return np.flip(myl, axis=0)
    elif d=='h':
        return np.flip(myl, axis=1)

Solution 2

I have found what may be the issue, when you assign a list to another list m = myl you are not creating a new copy of that list to play around with, so any changes to m will affect myl. By replacing that with tempm = m.copy() you get a new version of the list that can be bent to your will. The following should work nicely:

def matrixflip(m,d):
    tempm = m.copy()
    if d=='h':
        for i in range(0,len(tempm),1):
                tempm[i].reverse()
    elif d=='v':
        tempm.reverse()
    return(tempm)
Share:
15,323

Related videos on Youtube

Anandharajan T.R.V.
Author by

Anandharajan T.R.V.

Updated on June 04, 2022

Comments

  • Anandharajan T.R.V.
    Anandharajan T.R.V. almost 2 years

    I am trying to write a python function to flip a matrix horizontal or vertical. To write a Python function matrixflip(m,d) that takes a two-dimensional matrix and a direction, where d is either 'h' or 'v'. If d == 'h', the function should return the matrix flipped horizontally. If d == 'v', the function should return the matrix flipped vertically. For any other values of d, the function should return m unchanged. In all cases, the argument m should remain undisturbed by the function.

    import numpy as np
    def matrixflip(m,d):
        m = myl
        myl = np.array([[1, 2], [3, 4]])
        if d=='v': 
            return np.flip(contour, axis=0)
        elif d=='h':
            return np.flip(contour, axis=1)
    

    I expect the output as

    >>> myl = [[1,2],[3,4]]
    
    >>> myl
    [[1, 2], [3, 4]]  
    
    >>> matrixflip(myl,'h')
    [[2, 1], [4, 3]]
    
    >>> myl
    [[1, 2], [3, 4]]  
    
    >>> matrixflip(myl,'v')
    [[3, 4], [1, 2]]  
    
    >>> myl
    [[1, 2], [3, 4]]