Home > Net >  How to add two elements of arrays with each others and have a new array with a new shape?
How to add two elements of arrays with each others and have a new array with a new shape?

Time:02-10

I have the following two numpy arrays 'a' and 'b':

a = np.array([[1, -1], [1, 0], [1, 1]]) with a shape = (3, 2)
b = np.array([[1, 1], [2, 2]]) with shape = (2, 2)

I want to add each element of the 'b' array with each element of the 'a' array so that I have as an output the following 'c' array

c = np.array([[2, 0], [2, 1], [2, 2], [3, 1], [3, 2], [3, 3]]) with a shape = (6, 2)

Is the any function that can do it? Thanks

CodePudding user response:

An idea is to repeat b for the number of rows of a. And to tile a given the number of rows of b. This would work for any number of columns or rows, provided both arrays have the same number of columns.

import numpy as np

a = np.array([[1, -1], [1, 0], [1, 1]])
b = np.array([[1, 1], [2, 2]])

c = np.repeat(b, a.shape[0], axis=0)   np.tile(a, (b.shape[0], 1))

A larger example:

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 200, 300]])

c = np.repeat(b, a.shape[0], axis=0)   np.tile(a, (b.shape[0], 1))

gives:

[[11, 22, 33],
 [14, 25, 36],
 [17, 28, 39],
 [41, 52, 63],
 [44, 55, 66],
 [47, 58, 69],
 [71, 82, 93],
 [74, 85, 96],
 [77, 88, 99],
 [101, 202, 303],
 [104, 205, 306],
 [107, 208, 309]]

CodePudding user response:

That's the simplest calculation I could come up with:

c = np.array([a   b[0,:], a   b[1,:]]).reshape(6, 2)
  • Related