Question

I am trying to write some code to normalize a vector with elements [x,y,z] but was wondering if there is a way to normalize the elements so that each time the sum of elements will add to 1.

I did come across a formula: (pseudo code)

normalized = vectorA/ magnitude(vectorA)

However, if the vectorA = [1,4,5] then using the formula above would give:

magnitude = sqrt(1^2 + 4^2 + 5^2)
magnitude = sqrt(42)
magnitude = 6.48

Now based on that if I divide each element of the vector by 6.48 then:

1/6.48 = 0.154
4/6.48 = 0.62
5/6.48 = 0.77

As you can see, the sum is more than 1, so the formula doesn't work everytime and I was wondering if anyone has an idea on how to get the sum of elements to equal to 1 at all times.

Any help will be appreciated

Was it helpful?

Solution

Let's start with a diagram:

  B-------C
 /|      /|
A-------* |
| *-----|-G
|/      |/
*-------*

and let's further state that AG is your vector. For simplicity, we'll state that A is the origin [0, 0, 0].

If your intent is to simply scale the values (lengths of AB, BC and CG) in a linear fashion so that they total one, you simply divide each by the sum:

/   x       y       z   \
| ----- , ----- , ----- |
\ x+y+z   x+y+z   x+y+z /

In your particular case where x+y+z gives you 10, you end up with:

[0.1, 0.4, 0.5]

which sums up to one.


That formula that you found applies to three-dimensional vectors where you want the length of the vector AG to be one.

And the figures you have for that are (roughly) correct since the length of a vector is:

                 2              2            2
  sqrt (   height     +    width    +   depth )

= sqrt (0.154 * 0.154 + 0.62 * 0.62 + 0.77 * 0.77)
= sqrt (  0.023716    +   0.3844    +   0.5929  )
= sqrt (                 1.001016               )

= 1.000507871

Plugging your figures into that gives you something close to 1.0005 which is understandable given the rounding of your original numbers.

So, bottom line, if you want the length of the vector to be one, simply use the formula you posted in the question. If you want the vector co-ordinates to sum to one, just scale them based on the sum of the three co-ordinates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top