Dec-13-2022, 10:22 AM
I'm using here a"vectorized" form instead of using loops; vectorization is much faster as you'll notice.
Remarks:
Test the following codes to compare the vectorization and (classical) loops => you'll figured out how it works.
Hope it helps
Remarks:
- The Matrix array is just an example, you can useyour own A,B,C instead
- D is intialized to avoid (memory) dynamic allocation; it's a good practise
- i is the "index" vector (from 1 to (r-1))
- D is obvious here - based on your formula
- finally the first row corresponds to index i=0
- if your working only with integer, it might have been more relevant in my previous post to directly define the dtype for D/D2
- since the first row uses a different formula, so it can be calculated before of after the main block
Test the following codes to compare the vectorization and (classical) loops => you'll figured out how it works.
Hope it helps
import numpy as np import time Nmax = 10_000 r, c = 1_000_000, 3 # Matrix = np.random.randint(1, Nmax, size=(r,c)) Matrix = np.arange(r*c).reshape(r, c) # for all the matrix except the first row t0=time.time() D = np.zeros((r, 1), dtype=int) i = np.arange(1, r) D[i, 0] = Matrix[i-1, 2] - Matrix[i, 0] + Matrix[i, 1] # specifically for the first row i = 0 D[i, 0] = Matrix[i, 2] + Matrix[i, 0] - Matrix[i, 1] t1 = time.time() print(f"Duration1 = {t1-t0}") # using loops t2=time.time() D2 = np.zeros((r, 1), dtype=int) for i in range(1, r): D2[i, 0] = Matrix[i-1, 2] - Matrix[i, 0] + Matrix[i, 1] D2[0, 0] = Matrix[0, 2] + Matrix[0, 0] - Matrix[0, 1] t3=time.time() print(f"D equals D2? => {np.array_equal(D, D2)}") print(f"Duration2 = {t3-t2}") print(f"Duration's ratio = {(t3-t2)/(t1-t0)}")