How should I normalize a vector in Matlab where the sum is 1?

dragonmnl picture dragonmnl · Jun 27, 2012 · Viewed 22.8k times · Source

I need to normalize a vector of N integers so that:

  • Each value is proportional to its original value (the value will be between 0 and 1)
  • The sum of all values is =1

For instance:

If I have a vector

V = [2,2,1,0]

the normalized vector should should be:

V_norm = [0.4,0.4,0.2,0]  % 0.4+0.4+0.2 = 1

I tried with many solutions found in this community and on the web and finally I did it with this code:

part = norm(V);
if part > 0
  V_norm = V/part;
else % part = 0 --> avoid "divide by 0" 
  V_norm = part;
end

The problem this works if:

  • all elements of array are "0" --> resultant array doesn't change
  • only one element of the array is >0 and all other elements are = 0 --> resultant array: the element >0 is 1 and the other 0

but if I have a different case,although the result is proportional,the sum is not 0. For instance:

   V = [1,0,1]
   V_norm = [0.74,0,0.74]

   V = [1,1,1]
   V_norm = [0.54,0.54,0.54]

(I'm not sure if the number are correct because I can't use Matlab right now but I'm sure the sum is > 1 )

Ahy hint?

Thank you in advance

Answer

Ole Thomsen Buus picture Ole Thomsen Buus · Jun 27, 2012

What you need to do is, I believe, normalize using the 1-norm (taxicab norm):

v = [2, 2, 1, 0];
v_normed = v / norm(v, 1); % using the 1-norm

Variable v_normed should now be [0.4, 0.4, 0.2, 0.0]. The 1-norm of v_normed will equal 1. You can also sum the vector (similar to the 1-norm, but without applying the absolute function to each value), but the range of that sum will be between -1 to 1 in the general case (if any values in v are below 0). You could use abs on the resulting sum, but mathematically it will no longer qualify as a norm.