You can create a linear vector (a vector with evenly spaced elements) in MATLAB using the linspace
function.
Here's a breakdown of how to use linspace
:
% Create a row vector with 100 elements between 0 and 1 (inclusive).
y = linspace(0, 1);
% Create a row vector with n elements between x1 and x2 (inclusive).
y = linspace(x1, x2, n);
Explanation
-
linspace(x1, x2)
: This creates a row vector containing 100 evenly spaced points betweenx1
(the starting value) andx2
(the ending value). The default number of points is 100 if not specified. -
linspace(x1, x2, n)
: This creates a row vector containingn
evenly spaced points betweenx1
andx2
.x1
: The first element of the vector.x2
: The last element of the vector.n
: The number of elements in the vector.
The spacing between the points is calculated as
(x2 - x1) / (n - 1)
.
Examples
-
Creating a vector from 1 to 10 with 5 elements:
vector1 = linspace(1, 10, 5) % Output: vector1 = [1.0000, 3.2500, 5.5000, 7.7500, 10.0000]
-
Creating a vector from 0 to pi with 50 elements:
vector2 = linspace(0, pi, 50) % Output: A 1x50 vector with values from 0 to pi.
-
Using the default 100 points:
vector3 = linspace(0, 5) % Output: A 1x100 vector with values from 0 to 5.
Important Considerations
-
The
linspace
function always includes both the starting value (x1
) and the ending value (x2
) in the resulting vector. -
If
n
is 1, then the vector contains only the valuex1
. -
If
x1
andx2
are complex, thenlinspace
generates evenly spaced complex numbers.
Alternatives
While linspace
is the most direct approach, you can also create a linear vector using the colon operator (:
) and specify the increment:
x = 1:2:10 % Start at 1, increment by 2, and end at or before 10
%Output: x = [1 3 5 7 9]
However, the colon operator requires specifying the increment, and it might not always guarantee the inclusion of the exact end value like linspace
does. Therefore, linspace
is generally preferred for creating precise linearly spaced vectors.
In summary, linspace
provides a straightforward and reliable way to generate linear vectors in MATLAB, allowing you to control the start, end, and number of points in the vector.