Vectors are fundamental data structures in MATLAB, representing one-dimensional arrays of numbers. They form the backbone of many mathematical and scientific computations.
In MATLAB, you can create vectors using several methods:
The most common way to create a vector is by using square brackets:
row_vector = [1 2 3 4 5];
column_vector = [1; 2; 3; 4; 5];
For creating evenly spaced vectors, use the colon operator:
vector = 1:5; % Creates [1 2 3 4 5]
vector = 1:0.5:3; % Creates [1 1.5 2 2.5 3]
MATLAB offers functions for creating specific types of vectors:
zeros_vector = zeros(1, 5); % Creates [0 0 0 0 0]
ones_vector = ones(1, 5); % Creates [1 1 1 1 1]
random_vector = rand(1, 5); % Creates a vector of 5 random numbers
MATLAB provides powerful operations for working with vectors:
Perform operations on each element of a vector:
a = [1 2 3];
b = [4 5 6];
sum = a + b; % Results in [5 7 9]
product = a .* b; % Results in [4 10 18]
Apply mathematical functions to entire vectors:
v = [1 4 9 16];
sqrt_v = sqrt(v); % Results in [1 2 3 4]
Access and modify vector elements using indexing:
v = [10 20 30 40 50];
third_element = v(3); % Gets 30
v(2:4) = [25 35 45]; % Changes v to [10 25 35 45 50]
Useful functions for working with vectors:
length(v)
: Returns the number of elements in vsum(v)
: Calculates the sum of all elements in vmean(v)
: Computes the average of v's elementsmax(v)
and min(v)
: Find the maximum and minimum values in vUnderstanding vectors is crucial for effective MATLAB programming. They serve as building blocks for more complex MATLAB Data Types and are essential in various mathematical and scientific computations.