2.5 Built-in Functions

Many Python built-in functions and operations can be used with matrix arguments. We list some useful examples.

len(x)

Returns the product of the number of rows and the number of columns.

bool([x])

Returns False if x is empty (i.e., len(x) is zero) and True otherwise.

max(x)

Returns the maximum element of x.

min(x)

Returns the minimum element of x.

abs(x)

Returns a matrix with the absolute values of the elements of x.

sum(x[, start=0.0])

Returns the sum of start and the elements of x.

Matrices can be used as arguments to the list(), tuple(), zip(), map(), and filter() functions described in section 2.1 of the Python Library Reference. list(A) and tuple(A) construct a list, respectively a tuple, from the elements of A. zip(A,B,…) returns a list of tuples, with the ith tuple containing the ith elements of A, B, ….

>>> from cvxopt.base import matrix  
>>> A = matrix([[-11., -5., -20.], [-6., -0., 7.]])  
>>> B = matrix(range(6), (3,2))  
>>> list(A)  
[-11.0, -5.0, -20.0, -6.0, 0.0, 7.0]  
>>> tuple(B)  
(0, 1, 2, 3, 4, 5)  
>>> zip(A,B)  
[(-11.0, 0), (-5.0, 1), (-20.0, 2), (-6.0, 3), (0.0, 4), (7.0, 5)]

map(f,A), where f is a function and A is a matrix, returns a list constructed by applying f to each element of A. Multiple arguments can be provided, for example, as in map(f,A,B), if f is a function with two arguments.

>>> A = matrix([[5, -4, 10, -7], [-1, -5, -6, 2], [6, 1, 5, 2],  [-1, 2, -3, -7]])  
>>> B = matrix([[4,-15, 9, -14], [-4, -12, 1, -22], [-10, -9, 9, 12], [-9, -7,-11, -6]])  
>>> print matrix(map(max, A, B), (4,4))   # takes componentwise maximum  
[  5  -1   6  -1]  
[ -4  -5   1   2]  
[ 10   1   9  -3]  
[ -7   2  12  -6]

filter(f,A), where f is a function and A is a matrix, returns a list containing the elements of A for which f is true.

>>> filter(lambda x: x%2, A)         # list of odd elements in A  
[5, -7, -1, -5, 1, 5, -1, -3, -7]  
>>> filter(lambda x: -2 < x < 3, A)  # list of elements between -2 and 3  
[-1, 2, 1, 2, -1, 2]

It is also possible to iterate over matrix elements, as illustrated in the following example.

>>> A = matrix([[5, -3], [9, 11]])  
>>> for x in A: print max(x,0)  
...  
5  
0  
9  
11  
>>> [max(x,0) for x in A]  
[5, 0, 9, 11]

The expression ”x in A” returns True if an element of A is equal to x and False otherwise.