Home > front end >  How to add the same vector to all vectors in numpy array without loops?
How to add the same vector to all vectors in numpy array without loops?

Time:10-05

I am trying to plot a 3D mathematical expression using numpy and matplotlib:

The mathematical expression is:

Z(x,y) = exp[(v - v_t)*(v - v_t)']

while:

v= [x, y] and v_t = [x_t, y_t]

initiating vectors through the following code:

import numpy as np
CONST = 1
x = np.linspace(-5,5,20)
y = np.linspace(-5,5,20)
v = np.array([x,y])
v_t = np.array([CONST,CONST])

The question is, how can I execute the subtraction of v_t from each vector in array v, in a single command without looping?

the result should be something like so:

v = ([-5, -4, ... , 4, 5], [-5, -4, ... , 4, 5])

v_t = ([1,1])

v - v_t = (x_i - CONST, y_i - CONST) = ([-6, -5, ... , 3, 4],[-6, -5, ... , 3, 4])

CodePudding user response:

In [63]: CONST = 1
    ...: x = np.linspace(-5,5,11)
    ...: y = np.linspace(-5,5,11)
    ...: v = np.array([x,y])
    ...: v_t = np.array([CONST,CONST])

The resulting arrays and shapes:

In [64]: v
Out[64]: 
array([[-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.,  5.],
       [-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.,  5.]])
In [65]: v_t
Out[65]: array([1, 1])
In [66]: v.shape
Out[66]: (2, 11)
In [67]: v_t.shape
Out[67]: (2,)

By the rules of broadcasting, we need to change v_t to (2,1):

In [68]: v - v_t[:,None]
Out[68]: 
array([[-6., -5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.],
       [-6., -5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.]])

CodePudding user response:

In your code vector v has shape (N, 2) (where N is 20). Now if you want to use the advantage of broadcasting in numpy, you can add a new axis inorder to reshape vector v_t into (2, 1) and then directly subtract v_t from v. This way -

import numpy as np
CONST = 1
x = np.linspace(-5,5,20)
y = np.linspace(-5,5,20)
v = np.array([x,y])
v_t = np.array([CONST,CONST])
sub = (v - v_t[:, np.newaxis])
sub.shape # (2, 20)
  • Related