Reputation: 5146
I am trying to find an efficient way to multiply specific values within a matrix for a given scalar. Let's see a quick example.
Given a matrix M of values between 1 and 10 like so:
I want to multiply every cell that has value smaller than 3, by 2. Now I know I can find the coordinates of all items that have value 1 in tensorflow with tf.where(M < 3)
but I am struggling to find a good scalable solution to attain what I want. The transformation should be something like this:
How can I leverage this info to multiply only the cells at the given coordinates by 2 ?
Keep in mind that my matrices might be mich bigger than 3x3
Upvotes: 0
Views: 487
Reputation: 5146
I found out how to do this in tensorflow without having to do any transformation from numpy to tensorflow and vice-versa.
my_matrix = tf.constant([[1, 5, 8], [2, 2, 2], [9, 7, 6]])
result = tf.where(
tf.less(my_matrix, tf.constant(3)),
tf.scalar_mul(2, my_matrix),
my_matrix
)
@Josh answer helped me look into the right direction
Upvotes: 0
Reputation: 318
M = np.array([[1, 5, 8],[2, 2, 2], [9, 7, 6]])
M[M==1] = 2
print(M)
array([[2, 5, 8],
[2, 2, 2],
[9, 7, 6]])
Upvotes: 2