Reputation: 31
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]]
Upvotes: 2
Views: 29084
Reputation: 11
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)
Upvotes: 1
Reputation: 31
def matrixflip(m,d):
if d=='h':
m=myl
for i in range(0,len(m),1):
m[i].reverse()
return(m)
elif d=='v':
m=myl
m.reverse()
return(m)
else:
return(m)
Upvotes: 0
Reputation: 754
Interesting question. You can use the numpy function flip.
import numpy as np
myl = [[1,2],[3,4]]
For horizontal flip use index 0:
myl_flip_h = np.flip(myl,0) # horizontal flip
>> array([[2, 1],
[4, 3]])
For vertical flip use index 1:
myl_flip_v = np.flip(myl,1) # vertical flip
>>array([[3, 4],
[1, 2]])
Upvotes: 1
Reputation: 1
def matrixflip(a,b):
temp=[]
for i in range(len(a)):
temp=temp+[a[i][:]]
if b=='h':
for i in range(0,len(temp),1):
temp[i].reverse()
elif b=='v':
temp.reverse()
return(temp)
Upvotes: 0
Reputation: 1
def matrixflip(a,b):
temp=[]
for i in range(len(a)):
temp=temp+[a[i][:]]
if b=='h':
for i in range(len(temp)):
temp[i].reverse()
i=i+1
return temp
elif b=='v':
temp.reverse()
return(temp)
Upvotes: 0
Reputation: 1
Try this one
def matrixflip(a,b):
temp=[]
for i in range(len(a)):
temp=temp+[a[i][:]]
if b=='h':
for i in range(len(temp)):
temp[i].reverse()
return(temp)
elif b=='v':
temp.reverse()
return(temp)
Upvotes: 0
Reputation: 2298
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)
Upvotes: 1