Open In App

Linearly Spaced Vector in MATLAB

Improve
Improve
Like Article
Like
Save
Share
Report

Linearly spaced vectors are vectors that have values with equal differences in a linear domain. More clearly, say one wants to divide a domain [1,2] in intervals with 5 points or vectors so, the resultant vector would be [1.0, 1.25, 1.50, 1.75, 2.0]. This new vector is what we call a linearly spaced vector. Now, MATLAB provides a very simple function to create this linearly spaced vector, the linspace() function. 

Syntax:

linspace(<start_point>, <end_point>, (optional)<number_of_vectors>)

The linspace function takes three arguments, two mandatory and one optional argument. 

Let us look through various uses of the linspace function.

Example 1: 

Matlab




% Matlab code for Linearly
% Spaced Vector
  x = linspace(1,5);
  y = x.^2;
  stem(x,y)


Output:

 

Here, we divide the range (1,5) into 100 linearly spaced vectors. Now, it must be noted that if the number of vectors is not specified then, linspace divides the given range into 100 vectors by default. The output of the above code gives a plot with 100 points, to see the visual representation of these 100 linearly spaced vectors. Here you can see the 100 linearly spaced vectors plotted. 

Let’s see another example where we specify the number of vectors to be generated.

Example 2:

Matlab




% Matlab code for linspace
  x = linspace(1,5,5)


Output:

 

Thus, the linspace() function could be used to make linearly spaced vectors with the above two options.

Creating Linearly Spaced Vectors Using “:” Operator:

MATLAB provides another way of creating linearly spaced vectors i.e., using the ‘:’ operator. 

Syntax:

vector_name = start:step:end

Here, the start and end are the terminal points of the vector and the optional operand step is the difference between two vector points. The default step value is 1. 

The key difference between linspace() and ‘:’ is that linspace creates vectors based on a number of vectors whereas the ‘:’ operator creates vectors based on the difference between two vectors. One could use either method depending on their usage.

Example 3:

Matlab




% MATLAB code for ":"
  x = 1:5
  y = 1:0.5:3


Output:

 

Conclusion:

This article explained different methods of creating linearly spaced vectors in MATLAB.



Last Updated : 28 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads