Home > Net >  how to produce a matrix of the x[0] y[0], x[1] y[0]....... x[n] y[n]
how to produce a matrix of the x[0] y[0], x[1] y[0]....... x[n] y[n]

Time:07-02

I have a list x and y, both are list of list and trying to produce a matrix of the add up of each element of the each list

x = numpy.array ([[1,1,1,1],[2,2,2,2]])
y = numpy.array ([[0,1,2,3],[4,5,6,7]])

result: [x[0] y[0], x[0] y[1], x[1] y[0], x[1] y[1]]
=> numpy.array ([[1,2,3,4],[5,6,7,8],[2,3,4,5],[6,7,8,9]])

Do I have to reshape y before production? Is there any smarter and more effective way achieve it?

Thanks you

CodePudding user response:

You can express the sum of all row combinations between the two arrays using numpy.repeat and numpy.tile:

import numpy as np

x = np.array ([[1,1,1,1],[2,2,2,2],[3,3,3,3]]) 
y = np.array ([[0,1,2,3],[4,5,6,7]]) 

x_height = x.shape[0]
y_height = y.shape[0]

result = np.repeat(x, y_height, axis=0)   np.tile(y, (x_height, 1))
print(result)

results in

[[ 1  2  3  4]   # x[0]   y[0]
 [ 5  6  7  8]   # x[0]   y[1]
 [ 2  3  4  5]   # x[1]   y[0]
 [ 6  7  8  9]   # x[1]   y[1]
 [ 3  4  5  6]   # x[2]   y[0]
 [ 7  8  9 10]]  # x[2]   y[1]

This generalizes to x and y with arbitrary numbers of rows.

CodePudding user response:

With broadcasting followed by a reshape:

In [138]: x
Out[138]: 
array([[1, 1, 1, 1],
       [2, 2, 2, 2]])

In [139]: y
Out[139]: 
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

In [140]: (np.expand_dims(x, 1)   y).reshape(-1, x.shape[-1])
Out[140]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [2, 3, 4, 5],
       [6, 7, 8, 9]])
  • Related