MATLAB - Magnitude of a Vector


Magnitude of a vector v with elements v1, v2, v3, …, vn, is given by the equation −

|v| = √(v12 + v22 + v32 + … + vn2)

You need to take the following steps to calculate the magnitude of a vector −

  • Take the product of the vector with itself, using array multiplication (.*). This produces a vector sv, whose elements are squares of the elements of vector v.

    sv = v.*v;

  • Use the sum function to get the sum of squares of elements of vector v. This is also called the dot product of vector v.

    dp= sum(sv);

  • Use the sqrt function to get the square root of the sum which is also the magnitude of the vector v.

    mag = sqrt(s);


Create a script file with the following code −

Live Demo
v = [1: 2: 20];
sv = v.* v;       %the vector with elements 
                  % as square of v's elements
dp = sum(sv);     % sum of squares -- the dot product
mag = sqrt(dp);   % magnitude

When you run the file, it displays the following result −



E-Books Store