MATLAB by Example: Vectors
Vectors are essentially 1D matrices. This sample demonstrates row and column vectors, and the colon operator.
Code
% Row vector
row_vec = [1 2 3 4 5];
% Column vector
col_vec = [1; 2; 3; 4; 5];
% Creating vectors with colon operator
% start:step:end
v1 = 1:10; % 1, 2, ..., 10 (step 1 default)
v2 = 0:2:10; % 0, 2, 4, 6, 8, 10
v3 = 10:-1:1; % 10, 9, ..., 1
% linspace for fixed number of points
% linspace(start, end, number_of_points)
v4 = linspace(0, 1, 5); % 0, 0.25, 0.5, 0.75, 1.0
% Vector operations
mag = sqrt(sum(row_vec .^ 2));Explanation
Vectors in MATLAB are just matrices with one dimension equal to 1. A row vector is created by separating elements with spaces or commas, while a column vector uses semicolons. You can convert between them using the transpose operator '. Vectors are widely used for representing signals, time series, or lists of parameters.
The colon operator : is one of the most powerful tools in MATLAB for creating vectors. The syntax start:step:end generates a sequence of numbers. If the step is omitted, it defaults to 1. This is commonly used for defining time vectors or loop indices. For example, 0:0.1:1 creates a vector from 0 to 1 with increments of 0.1.
Alternatively, the linspace function allows you to generate a linearly spaced vector by specifying the number of points rather than the step size. linspace(x1, x2, n) generates n points between x1 and x2. This is particularly useful when plotting functions, as it ensures you have a specific resolution over an interval.
Code Breakdown
1:10 creates a vector containing integers from 1 to 10 inclusive.linspace(0, 1, 5) generates 5 points: 0.00, 0.25, 0.50, 0.75, 1.00.
