user1700890
user1700890

Reputation: 7730

Tensorflow: multiply matrix columns by elements of vector and get matrix back

Here is what I would like to accomplish in Tensorflow.

I have 2x2 matrix (trainable)

x_1 x_2
x_3 x_4

and I have input vector

a
b

I would like to multiply each column of matrix by element of vector and get back the following matrix

ax_1 bx_2
ax_3 bx_4

I can get this result by declaring each column of matrix as separate variable, but I wonder if there is more elegant solution.

Upvotes: 1

Views: 1312

Answers (1)

MatthewScarpino
MatthewScarpino

Reputation: 5936

Thanks to broadcasting, you should be fine using the regular multiplication operator:

import tensorflow as tf

x = tf.constant([[3, 5], [7, 11]], dtype=tf.int32)
a = tf.constant([4, 8], dtype=tf.int32)
y = x * a

with tf.Session() as sess:
    print(sess.run(y))  # Result: [[12, 40], [28, 88]]

Upvotes: 1

Related Questions