1

I have an example array like so:

x = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]], [[2, 2, 2], [2, 2, 2], [2, 2, 2]], [[3, 3, 3], [3, 3, 3], [3, 3, 3]]])

I can multiply all values by 2 without issues:

print(x * 2)

>>> [[[2 2 2]
  [2 2 2]
  [2 2 2]]

 [[4 4 4]
  [4 4 4]
  [4 4 4]]

 [[6 6 6]
  [6 6 6]
  [6 6 6]]]

Great!

What I need to do is multiple all arrays in the first "column" by 2, on the second "column" by 4 and on the third "column" by 3, such that:

print(result)

>>> [[[2 2 2]
  [4 4 4]
  [3 3 3]]

 [[4 4 4]
  [8 8 8]
  [6 6 6]]

 [[6 6 6]
  [12 12 12]
  [9 9 9]]]

Is there a numpy syntax to make this one go, like I did by multiplying by 2?

1 Answer 1

2

Make the factors a 3 X 1 array, and then multiply it with x:

x * np.array([2,4,3]).reshape(-1, 1)

#[[[ 2  2  2]
#  [ 4  4  4]
#  [ 3  3  3]]

# [[ 4  4  4]
#  [ 8  8  8]
#  [ 6  6  6]]

# [[ 6  6  6]
#  [12 12 12]
#  [ 9  9  9]]]

You can read more about numpy broadcasting here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.