Tuesday, January 5, 2021

Python - Create an empty array and apply maximum/minimum clipping limits to a vector

 The code below shows how to

1. Define array a as type = float 32. (aka Single in Matlab)

2. Create empty array of zeros b as the same shape and type as a

3. Apply min/max limits to a and the clipped results to b

4. Make a copy of as c and apply the same min/max clipping limits.

import numpy as np

#Array of float32. Without dtype, the default is float64.

a = np.array([0.21, 0.92, 0.89, 1.67, -0.12],dtype=np.float32)


#Create b with the same dimension as a

b = np.zeros(a.shape,dtype=a.dtype)


#clip

np.clip(a,0,1,out=b);


#make a copy of a as c. If use = c, the content of will change with c.

c = a.copy()

c[c>1]=1

c[c<0]=0

Variable explorer results with Spyder:



Reference:

Single-precision floating-point (Wikipedia)