Hi, this is my first post, and im trying to compare a matrix to find the minus element greater than zero, my list is

matrix=
[9,8,12,15],
[0,11,15,18],
[0,0,10,13],
[0,0,0,5]

I dont want to use "min" function because each element is associated to (X,Y) position.

Thanks a lot !

jDSL

Hi, this is my first post, and im trying to compare a matrix to find the minus element greater than zero, my list is

matrix=
[9,8,12,15],
[0,11,15,18],
[0,0,10,13],
[0,0,0,5]

I dont want to use "min" function because each element is associated to (X,Y) position.

Thanks a lot !

jDSL

I'm confused by your desire not to use min -- are you saying that (unlike the example) -- each element is a member of R2? Perhaps a complex number?

Anyways, for the matrix above, you could do something like this:

min_value = min([min([elem for elem in row if elem > 0]) for row in matrix])

This creates a list of the minimums of the non-zero elements in each row, then finds the minimum of that list.

Example:

``````>>> def min_value(matrix):
return min([min([elem for elem in row if elem > 0]) for row in matrix])
>>> matrix=[[9,8,12,15],\
[0,11,15,18],\
[0,0,10,13],\
[0,0,0,5]]
>>> matrix
[[9, 8, 12, 15], [0, 11, 15, 18], [0, 0, 10, 13], [0, 0, 0, 5]]
>>> min_value(matrix)
5``````

If the elements don't properly behave under min, you could roll your own min function. However, it might be the case that there is no well-defined min for your type of object -- points in 2-space, for example, don't have a well-defined comparison function.

Hope it helps,
Jeff

Thank you so much.

Similar to Jeff's code:

``````# write this as a list of lists ...
matrix = [[9,8,12,15],
[0,11,15,18],
[0,0,10,13],
[0,0,0,5]]

# find the minimum value above val in each list
val = 0
for n in matrix:
print n  # test
mv = min([v for v in n if v > val])
print mv

"""
my output -->
[9, 8, 12, 15]
8
[0, 11, 15, 18]
11
[0, 0, 10, 13]
10
[0, 0, 0, 5]
5
"""``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.