0

I was trying to multiply and divide a numpy array's each sub numpy array with two numpy arrays.

I have a numpy array x with shape [100, 5], two numpy arrays y and y both with shape (5,).

I am trying to change the value of the tensor: For each sub numpy array w along with axis=0 in x, it should have shape [1, 5], I want to do (w - y)*z.

My thought was to for-loop over x and pick each sub array inside it to do this and then reconstruct the original array. However, this may be not efficient.

5
  • So, you want the ith column in x to have y[i] subtracted from it, and then multiplied by z[i]? Commented Dec 1, 2017 at 18:57
  • Yeah, it is, thanks. Commented Dec 1, 2017 at 18:58
  • Simply do : (x - y)*z? Commented Dec 1, 2017 at 19:01
  • @Divakar, thanks, but I am not sure if this is correct. I am not very familiar with numpy. Commented Dec 1, 2017 at 19:13
  • This should help with familiarity - docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html Commented Dec 1, 2017 at 19:14

1 Answer 1

1

This should work.

(x - y) * z

sample:

>>> x.shape,y.shape, z.shape
((10L, 5L), (5L,), (5L,))
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49]])
>>> y
array([0, 1, 2, 3, 4])
>>> z
array([1, 2, 3, 4, 5])

>>> (x-y)*z
array([[  0,   0,   0,   0,   0],
       [  5,  10,  15,  20,  25],
       [ 10,  20,  30,  40,  50],
       [ 15,  30,  45,  60,  75],
       [ 20,  40,  60,  80, 100],
       [ 25,  50,  75, 100, 125],
       [ 30,  60,  90, 120, 150],
       [ 35,  70, 105, 140, 175],
       [ 40,  80, 120, 160, 200],
       [ 45,  90, 135, 180, 225]])
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.