mathajax

Vector normalization - Unit vector

A vector can converted into unit vector by vector normalization in which each elements of the vector is divided by that vector's norm or length.

Vector X


X vector

Unit Vector X


unit vector equation

Java code - vector normalization

The following code converts a vector into unit vector by vector normalization. A vector is defined in Java program by a integer array or a double array.

Example

Vector X = [5.0, 1.2, 2.0] , find unit vector of X by normalization.
1. find vector X norm

|| X ||   =  sqrt  ( 5.0^2 + 1.2^2 + 2.0 ^2 )
          =  sqrt  ( 25.0  +  1.44 + 4.0 )
          =  sqrt  ( 30.44)  
          =  5.5172
2 Unit vector X      = [ 5.0/5.5172 , 1.2/5.5172 , 2.0/5.5172]                 
                     = [ 0.9062, 0.2175, 0.3625].




import java.util.Arrays;

public class Vector
 {
 
   public static double[] unit_vector(double vec[]) 
   {
     int nelement = vec.length; 
     double uvec[] = new double[nelement];
  
    double nrm =0.0;  
    for(int n=0;n<nelement;n++)
      nrm += (vec[n]*vec[n]);
    
    double enrm = Math.sqrt(nrm);
  
    for(int n=0;n<nelement;n++)
       uvec[n] = vec[n]/ enrm;
    return uvec;
   }
 
  public static double[] unit_vector(int vec[]) 
    {
    
     int nelement = vec.length; 
     double uvec[] = new double[nelement];
     double nrm =0.0;
  
     for(int n=0;n<nelement;n++)
       nrm += (vec[n]*vec[n]);
    
     double enrm = Math.sqrt(nrm);  
  
  
     for(int n=0;n<nelement;n++)
       uvec[n] = vec[n]/ enrm;
     return uvec;  
   }

 
 public static void main(String[] args) {
  
  System.out.println( "\n Find unit vector \n ");
  double U[]={5.0 ,1.2 , 2.0};  
    
  System.out.println( "\nVector U ");
  System.out.println( Arrays.toString(U));
  double uvec[] = Vector.unit_vector(U);
  System.out.println( "Unit Vector U  ");
  System.out.println( Arrays.toString(uvec)  );

  
  int V[] = {2, -1, 3};
  System.out.println( "\n Vector V ");
  System.out.println( Arrays.toString(V));
  double uvec2[] = Vector.unit_vector(V);
  System.out.println( "Unit Vector V  ");
  System.out.println( Arrays.toString(uvec2) );
   

 }

}


Output


Find unit vector of a vector

Vector U :[5.0, 1.2, 2.0]
Unit Vector U  :[0.9062, 0.21749, 0.36249]

Vector V :[2, -1, 3]
Unit Vector V :[0.53452, -0.26726, 0.80178]

Comments

Popular posts from this blog

Matrix Forward and Back Substitution

Chebyshev distance between two points

Solve System of Linear Equations by LU Decompose

Complex number Multiplication and Division

Matrix Determinant, Matrix Adjoint and Matrix Inverse