braket an matrix in python

Peter Otten __peter__ at web.de
Mon Feb 3 13:16:20 EST 2020


Parisa Ch wrote:

> x=np.linspace(0,2*math.pi,n)
> n=len(x)
> r=int(math.ceil(f*n))
> h=[np.sort(np.abs(x-x[i]))[r] for i in range(n)]
> 
> this is part of a python code. the last line is confusing? x is a matrix
> and x[i] is a number. how  calculate x-x[i] for each i?
>  why the put r in [] ?

Brake it appart:

y = x - x[i]  # the numpy feature that makes that possible is called
              # "broadcasting"

subtracts the value x[i] from every entry in the vector x

z = np.abs(y)

calculates the absolute value of every entry in y.

t = np.sort(z)

sorts the values in z and finally, assuming r is an integer,

u = t[r]  

looks up a single scalar in the vector.

The enclosing "list comprehension" [expr for item in iterable] builds a list 
of n values calculated as sketched above.



More information about the Python-list mailing list