0

I have a tensor array a and a tensor matrix m. Now I want to insert a into m after every second position started at index 0 ending with len(m)-2. Let's make an equivalent example using numpy and plain python:

# define m
m = np.array([[3,7,6],[4,3,1],[8,4,2],[2,8,7]])
print(m)
#[[3 7 6]
# [4 3 1]
# [8 4 2]
# [2 8 7]]

# define a
a = np.array([1,2,3])
#[1 2 3]

# insert a into m
result = []
for i in range(len(m)):
    result.append(a)
    result.append(m[i])
print(np.array(result))
#[[1 2 3]
# [3 7 6]
# [1 2 3]
# [4 3 1]
# [1 2 3]
# [8 4 2]
# [1 2 3]
# [2 8 7]]

I am looking for a solution in tensorflow. I am convinced that there is a solution that doesn't need a loop but I am not able to find one. I hope someone can help me out with this!

maxx2803
  • 33
  • 3

2 Answers2

0

This should work,

np.ravel(np.column_stack((m, np.tile(a, (4, 1))))).reshape(8, 3)

For idea, please refer to Interweaving two numpy arrays. Apply any solution described there, and reshape.

Nadim Abrar
  • 186
  • 1
  • 7
  • Thanks for your answer, but I am looking for a solution in tensorflow! I only provided a numpy example for clarity. – maxx2803 Sep 23 '19 at 08:36
0

You can concatenate your target vector at the beginning of each line of your matrix, and then reshape it.

import tensorflow as tf

initial_array = tf.constant([
    [3, 7, 6],
    [4, 3, 1],
    [8, 4, 2],
    [2, 8, 7],
])

vector_to_add = [1, 2, 3]
concat = tf.concat([[vector_to_add] * initial_array.shape[0], initial_array], axis=1)  # Concatenate vector_to_add to each vector of initial_array
output = tf.reshape(concat, (2 * initial_array.shape[0], initial_array.shape[1]))  # Reshape
Raphael Meudec
  • 686
  • 5
  • 10