suppose a 2D numpy array has to be created from two 1D numpy arrays x and y. The fortran pseudocode is as follows:
do i = 1, n
do j = 1, m
A[i, j] = x[i]*y[j]
enddo
enddo
what is the most numpythonic way to create this 2D array this without using loops?
CodePudding user response:
The numpythonic way would be to use broadcasting.
You can do a broadcasting operation if the dimensions of your arrays are compatible based on two criteria. Starting from the rightmost dimensions:
they are equal
they are 1.
If you want there to be length-x number of rows, you could to give it an appropriate dimension, with 1, for it to be broadcast with the *
operation:
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> y = np.array([10, 11])
>>> print(x[:, None] , y, sep="\n"*2)
[[1]
[2]
[3]
[4]]
[10 11]
>>> x[:, None] * y
array([[10, 11],
[20, 22],
[30, 33],
[40, 44]])
Or using the other dimensions (corresponding to switching the orders of the loop):
>>> print(x , y[:, None], sep="\n"*2)
[1 2 3 4]
[[10]
[11]]
>>> x * y[:, None]
array([[10, 20, 30, 40],
[11, 22, 33, 44]])