title: How should I normalize a vector in Matlab where the sum is 1?
body: <p>I need to normalize a vector of N integers so that:</p>
  
  <ul>
  <li>Each value is proportional to its original value (the value will be between 0 and 1)</li>
  <li>The sum of all values is =1</li>
  </ul>
  
  <p>For instance:</p>
  
  <p>If I have a vector</p>
  
  <pre><code>V = [2,2,1,0]
  </code></pre>
  
  <p>the normalized vector should should be:</p>
  
  <pre><code>V_norm = [0.4,0.4,0.2,0]  % 0.4+0.4+0.2 = 1
  </code></pre>
  
  <p>I tried with many solutions found in this community and on the web and finally I did it with this code:</p>
  
  <pre><code>part = norm(V);
  if part &gt; 0
    V_norm = V/part;
  else % part = 0 --&gt; avoid "divide by 0" 
    V_norm = part;
  end
  </code></pre>
  
  <p>The problem this works if:</p>
  
  <ul>
  <li>all elements of array are "0" --> resultant array doesn't change</li>
  <li>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</li>
  </ul>
  
  <p>but if I have a different case,although the result is proportional,the sum is not 0.
  For instance:</p>
  
  <pre><code>   V = [1,0,1]
     V_norm = [0.74,0,0.74]
  
     V = [1,1,1]
     V_norm = [0.54,0.54,0.54]
  </code></pre>
  
  <p>(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 )</p>
  
  <p>Ahy hint?</p>
  
  <p>Thank you in advance</p>