Python - Select elements from matrix within range
<p>I have a question regarding python and selecting elements within a range.</p>

<p>If I have a n x m matrix with n row and m columns, I have a defined range for each column (so I have m min and max values).</p>

<p>Now I want to select those rows, where all values are within the range.</p>

<p>Looking at the following example:</p>

<pre><code>input = matrix([[1, 2], [3, 4],[5,6],[1,8]])
boundaries = matrix([[2,1],[8,5]])
#Note:
#col1min = 2
#col1max = 8
#col2min = 1
#col2max = 5
print(input)

desired_result = matrix([[3, 4]])
print(desired_result)
</code></pre>

<p>Here, 3 rows where discarded, because they contained values beyond the boundaries.</p>

<p>While I was able to get values within one range for a given array, I did not manage to solve this problem efficiently.</p>

<p>Thank you for your help.</p>

<p>Your example data syntax is not correct <code>matrix([[],..])</code> so it needs to be restructured like this:</p>

<pre><code>matrix = [[1, 2], [3, 4],[5,6],[1,8]]
bounds = [[2,1],[8,5]]
</code></pre>

<p>I'm not sure exactly what you mean by "efficient", but this solution is readable, computationally efficient, and modular:</p>

<pre><code># Test columns in row against column bounds or first bounds
def row_in_bounds(row, bounds):
    for ci, colVal in enumerate(row):
        bi = ci if len(bounds[0]) &gt;= ci + 1 else 0
        if not bounds[1][bi] &gt;= colVal &gt;= bounds[0][bi]:
            return False
    return True

# Use a list comprehension to apply test to n rows
print ([r for r in matrix if row_in_bounds(r,bounds)])
&gt;&gt;&gt;[[3, 4]]
</code></pre>

<p>First we create a reusable test function for rows accepting a list of bounds lists, tuples are probably more appropriate, but I stuck with list as per your specification.  </p>

<p>Then apply the test to your matrix of n rows with a list comprehension. If n exceeds the bounds column index or the bounds column index is falsey use the first set of bounds provided.</p>

<p>Keeping the row iterator out of the row parser function allows you to do things like get min/max from the filtered elements as required.  This way you will not need to define a new function for every manipulation of the data required.</p>

python