1
votes

I am trying to "combine" two vectors containing true and false values.

If i have a vector of 4 (rows) and and second one of 3 (columns, I want to create a 4x3 matrix where the values are an "OR" between the 1st and the 2nd vector values.

my code get below gets the desired output, but with a horrible runtime:

import numpy as np
import time

np_calc_rows = np.random.choice(a=[False, True], size=(12000,))
np_calc_cols = np.random.choice(a=[False, True], size=(1000,))

np_output = np.empty((12000,1000),dtype=bool)

start = time.time()
for i in range(0,len(np_calc_rows)):
    for j in range(0,len(np_calc_cols)):
        np_output[i,j] = np_calc_rows[i] or np_calc_cols[j]
print('runtime (ms): ' + str(time.time()-start))

Any attempts to get to the desired result using vector/matrix operations failed, how could I achieve this in an efficient way without the 2 loops ?

1

1 Answers

0
votes

Use broadcasting:

import numpy as np

np_calc_rows = np.random.choice(a=[False, True], size=(12000,))
np_calc_cols = np.random.choice(a=[False, True], size=(1000,))


np_output = np_calc_cols | np_calc_rows[:, np.newaxis]

print(np_output.shape)
print(np_output)

Output

(12000, 1000)
[[False  True False ...  True  True False]
 [False  True False ...  True  True False]
 [False False False ... False False False]
 ...
 [False False False ... False False False]
 [False  True False ...  True  True False]
 [False False False ... False False False]]