Home > database >  How can I use broadcasting to code my program in one line?
How can I use broadcasting to code my program in one line?

Time:10-09

I have a code that works fine, however, the exercise is to code it in one line using broadcasting and I've found it very complicated to do, this is the code:

import numpy as np

v1 = np.array([10, 20, 30, 40, 50])
v2 = np.array([0, 1, 2, 3 ])
matrix = []

for i in v1:
  matrix.append(i**v2)

matrixx = np.array(matrix).reshape([5,4])
print(matrixx)

Please some help!

CodePudding user response:

You don't need broadcasting (well it will occur automatically) in this case since both arrays have a dimension of size 1.
You can get the same output without loop/comprehension:

print(v1.reshape(5,1)**v2)
  • Related