Friday, 5 September 2025

MathABC: Vector-scalar multiplication

Scalars scale vectors without changing their direction. Scalars do not change the direction of the vector. But the figure shows that the vector direction flips when the scalar is negative (that is, its angle rotates by 180°).


When Scalar = 1/3, 0, -2/3






References:

Cohen, Mike X. Practical Linear Algebra for Data Science (pp. 31-32). O'Reilly Media. Kindle Edition. 


Code from the Book

   # import libraries

import numpy as np

import matplotlib.pyplot as plt



# NOTE: these lines define global figure properties used for publication.

import matplotlib_inline.backend_inline

matplotlib_inline.backend_inline.set_matplotlib_formats('svg') # display figures in vector format

plt.rcParams.update({'font.size':14}) # set global font size


# Effects of different scalars


# a list of scalars:

#scalars = [ 1, 2, 1/3, 0, -2/3 ]

scalars = [ 1/3, 0, -2/3 ]

baseVector = np.array([ .75,1 ])


# create a figure

fig,axs = plt.subplots(1,len(scalars),figsize=(12,3))

i = 0 # axis counter


for s in scalars:


  # compute the scaled vector

  v = s*baseVector


  # plot it

  axs[i].arrow(0,0,baseVector[0],baseVector[1],head_width=.3,width=.1,color='k',length_includes_head=True)

  axs[i].arrow(.1,0,v[0],v[1],head_width=.3,width=.1,color=[.75,.75,.75],length_includes_head=True)

  axs[i].grid(linestyle='--')

  axs[i].axis('square')

  axs[i].axis([-2.5,2.5,-2.5,2.5])

  axs[i].set(xticks=np.arange(-2,3), yticks=np.arange(-2,3))

  axs[i].set_title(f' = {s:.2f}')

  i+=1 # update axis counter


plt.tight_layout()

plt.savefig('Figure_02_03.png',dpi=300)

plt.show()


No comments:

Post a Comment