MATLAB - Vectors
MATLAB - Vectors
Section titled “MATLAB - Vectors”In MATLAB, a vector is a one-dimensional array of numbers. As MATLAB stands for Matrix Laboratory, vectors are the fundamental building block for nearly all data manipulation. Understanding vectors is the key to writing efficient, readable, and idiomatic MATLAB code through a powerful concept called vectorization.
MATLAB supports two types of vectors:
- Row Vectors: A 1xN array.
- Column Vectors: An Nx1 array.
Creating Vectors
Section titled “Creating Vectors”Manual Creation
Section titled “Manual Creation”Row vectors are created by enclosing elements in square brackets [], separated by spaces or commas.
% A row vectorrow_vec = [7 8 9 10 11]% or alternatively% row_vec = [7, 8, 9, 10, 11]Column vectors are created similarly, but elements are separated by semicolons ;.
% A column vectorcol_vec = [7; 8; 9; 10; 11]Programmatic Creation
Section titled “Programmatic Creation”It’s more common to create vectors using functions:
% Colon operator for uniformly spaced elements (step of 1)v1 = 1:5 % Result: [1 2 3 4 5]
% Colon operator with a specified stepv2 = 0:0.5:2 % Result: [0 0.5 1.0 1.5 2.0]
% `linspace` for a specific number of pointsv3 = linspace(0, 10, 5) % 5 points from 0 to 10. Result: [0 2.5 5 7.5 10]
% Pre-allocating a vector with zeros (good for performance)v4 = zeros(1, 4) % Result: [0 0 0 0]Accessing Vector Elements (Indexing)
Section titled “Accessing Vector Elements (Indexing)”You can access and modify vector elements using parentheses (). MATLAB indexing starts at 1.
v = [10 20 30 40 50];
% Access the third elementelem3 = v(3) % Result: 30
% Access the last element using the 'end' keywordlast_elem = v(end) % Result: 50
% Access a range of elements (a 'slice')sub_vec = v(2:4) % Result: [20 30 40]
% Access non-contiguous elementsnon_contig = v([1 4]) % Result: [10 40]
% Modify an elementv(1) = 99; % v is now [99 20 30 40 50]Logical Indexing
Section titled “Logical Indexing”A powerful feature is to access elements based on a logical condition. This is a cornerstone of vectorization.
v = [10 20 30 40 50];
% Find all elements greater than 25large_vals = v(v > 25) % Result: [30 40 50]Essential Vector Operations
Section titled “Essential Vector Operations”Operations on vectors are typically performed element-by-element.
a = [1 2 3];b = [4 5 6];
% Addition and Subtraction (vectors must be same size)sum_vec = a + b % Result: [5 7 9]diff_vec = b - a % Result: [3 3 3]
% Scalar multiplicationscaled_vec = a * 3 % Result: [3 6 9]
% Element-wise multiplication (NOTE the dot: .*)% This is NOT a dot product.elem_prod = a .* b % Result: [1*4, 2*5, 3*6] -> [4 10 18]
% Transpose (converts a row to a column and vice-versa)col_a = a' % Result: a 3x1 column vector
% Appending vectors (concatenation)horz_cat = [a, b] % Result: [1 2 3 4 5 6]vert_cat = [a'; b'] % Result: a 6x1 column vector
% Vector magnitude (Euclidean norm)mag = norm(a) % Result: sqrt(1^2 + 2^2 + 3^2) -> sqrt(14)
% Dot productdp = dot(a, b) % Result: 1*4 + 2*5 + 3*6 -> 32Common Mistake: * vs. .*
Section titled “Common Mistake: * vs. .*”The most common error for beginners is confusing matrix multiplication (*) with element-wise multiplication (.*).
a .* b(Element-wise): Multiplies corresponding elements.aandbmust have the same size. The result is a vector of the same size.a * b(Matrix Multiplication): Performs linear algebraic multiplication. For vectors, this is only defined if the inner dimensions agree (e.g.,row_vec * col_vecis a scalar dot product,col_vec * row_vecis a matrix outer product). Using this by mistake often leads to a ‘dimension mismatch’ error.
Practical Application: 2D Kinematics
Section titled “Practical Application: 2D Kinematics”Vectors are perfect for representing physical quantities like position, velocity, and acceleration.
% An object's initial position and velocity vectorspos0 = [10, 20]; % (x, y) position in metersvel = [5, -2]; % (vx, vy) velocity in m/s
% Time elapseddt = 2; % seconds
% Calculate the new position using vector additionpos1 = pos0 + vel * dt;
fprintf('New position is (%.1f, %.1f) meters.\n', pos1(1), pos1(2));
% Calculate the speed (magnitude of the velocity vector)speed = norm(vel);fprintf('Speed is %.2f m/s.\n', speed);