[SciPy-User] [SciPy-user] lambda functions within matrix

Warren Weckesser warren.weckesser@enthought....
Thu Apr 29 19:05:37 CDT 2010


archeryguru2000 wrote:
> Hello all,
> I'm trying to create a matrix that will allow me to specify which cells will
> contain certain values.  I have a line of code that I just cannot straighten
> out.  In SymPy I can use the following:
>
>   
>>>> sympy.Matrix(N,N,lambda i,j: i==j & j<int(M/2+1))
>>>>         
>
> where N and M are integers.  This creates a zero-matrix with ones in the
> upper left diagonal but the ones do not continue to the lower left.  However
> in SciPy, I assumed I would've used the following:
>
>   
>>>> scipy.fromfunction(lambda i,j: i==j & j<int(M/2+1), (N,N))
>>>>         
>
> but this gives an error that seems to pertain to my lambda function?
> unsupported operand type(s) for &: 'float' and 'float'
>
>   

In numpy, & has higher precedence than the relational operators == and 
<.  Use additional parentheses:

scipy.fromfunction(lambda i,j: (i==j) & (j<int(M/2+1)), (N,N))



For example:

In [16]: N = 4

In [17]: M = 2

In [18]: scipy.fromfunction(lambda i,j: (i==j) & (j<int(M/2+1)), (N,N))
Out[18]:
array([[ True, False, False, False],
       [False,  True, False, False],
       [False, False, False, False],
       [False, False, False, False]], dtype=bool)

In [19]: scipy.fromfunction(lambda i,j: (i==j) & (j<int(M/2+1)), 
(N,N)).astype(float)
Out[19]:
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])



Warren

> Any suggestions?
> Thanks,
> ~~archery~~
>   



More information about the SciPy-User mailing list