Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active April 4, 2018 08:54
Show Gist options
  • Select an option

  • Save jdmichaud/24c94ff68831ee7219906a2ab2a66fd0 to your computer and use it in GitHub Desktop.

Select an option

Save jdmichaud/24c94ff68831ee7219906a2ab2a66fd0 to your computer and use it in GitHub Desktop.
Normalize vector with numpy

So you want to normalize a vector? Well numpy can do that for you with a little help.

First include numpy:

!INCLUDE normalized.py 1:1

Then call the norm function of the linealg module:

!INCLUDE normalized.py 4:6

Encapsulate all this into a function:

!INCLUDE normalized.py

And now with graphics!

@startditaa
+--------+   +-------+    +-------+
|        +---+ ditaa +--> |       |
|  Text  |   +-------+    |diagram|
|Document|   |!magic!|    |       |
|     {d}|   |       |    |       |
+---+----+   +-------+    +-------+
	:                         ^
	|       Lots of work      |
	+-------------------------+
@endditaa

That's all folks!

title: Normalize a vector with numpy
import numpy as np
def normalized(a, axis=-1, order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return (a / np.expand_dims(l2, axis))[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment