[EN] ulab EP 6 compare

This article is EP 6 of the MicroPython ulab series, which is about the compare submodule for comparing ulab-generated arrays that Python did not originally support. This article describes the functions and usage of this submodule for further recognition and use.

compare

The compare submodule is used to compare 1D and 2D arrays to find similarities, differences, choose a larger one or smaller one. The four functions have the following usage patterns:

  1. result = ulab.comapre.clip( M, a, b ) It changes the value of every element less than a to a, and any element greater than b is changed to b just like maximum( a, minimum( M, b ) )
  2. result = ulab.comapre.clip( M, N, b ) If M and N have the same members, the operation compares the values of M with N. If any of the elements of M is less than N, the value of N is chosen, and if any value is greater than b, the value of b is chosen instead.
  3. result = ulab.compare.equal( M, N ) Comparing M and N, return True, if it is the same otherwise return False.
  4. result = ulab.compare.not_equal( M, N ) Comparing M and N, return True if they are different otherwise return False.
  5. result = ulab.comapre.maximum( M, N ) Compares M with N. If any element of both arrays is greater then it will be picked as a result of that sequence.
  6. result = ulab.comapre.minimum( M, N ) Compares M with N. If any element of an array is smaller, it will be selected as the value of the newly created array.

Example Code

Example code18-13 creates M and N int8 type arrays of 12, then compares that each member is the same, different or not. After that, find a lesser and greater array by comparing M and N. Finally, clip the data. The result is as shown in Figure 1.

# code18-13
import ulab as np

M = np.array(range(12), dtype=np.int8)
N = np.linspace(12,1,12,dtype=np.int8)

print("M == N ? {}".format(np.compare.equal(M, N)))
print("M != N ? {}".format(np.compare.not_equal(M, N)))
print("minimum(M,N) = {}".format(np.compare.minimum(M,N)))
print("maximum(M,N) = {}".format(np.compare.maximum(M,N)))
print("clip(M,5,10) = {}".format(np.compare.clip(M,5,10)))
print("clip(M,N,10) = {}".format(np.compare.clip(M,N,10)))

(Figure. 1 result of code18-13)

Conclusion

From this article, an array comparison is a head-to-head comparison with its members, so the number of both members must be the same. But there can be different types.  Because it compares the values ​​of each member, and in addition, the result of the comparison will be a new array with the same number of members as the compared array. But the data stored depends on the function being called, i.e. minimum function yields a new array where each member is the smallest value out of the two arrays. The clip function returns the result of the new array members that values are not less than a and not greater than b, etc.

Finally, have fun with programming.

(C) 2020, By Jarut Busarathid and Danai Jedsadathitikul
Updated 2021-08-19