MATLAB is short for Matrix Laboratory and is an environment based on matrix operations. All data in MATLAB is stored in the form of matrices or multidimensional arrays. Vectors and scalars are two special forms of matrices.
A vector refers to a matrix with a single row or a single column, and it is the foundation of matrices. To become proficient in MATLAB, one of the basic skills is to be able to manipulate vectors skillfully, as the characteristics of vector operations can enable vectorization of certain computations.
In many programming situations, vectorized code executes over 10 times faster than usual. Therefore, vectorization is one of the most common and effective means of writing quick MATLAB code.
1. Vector Assignment
Assignment is the process of assigning a value to an identifier that represents a constant or variable. In MATLAB, variables or constants represent matrices; a scalar can be viewed as a 1×1 matrix, while a vector can be seen as a 1×N (row vector) or N×1 matrix. The general form of an assignment statement is “variable = expression (or number).”
There are several ways to assign values to vectors:
(1) Assigning values to vectors using the vector construction operator (square brackets [ ]) and numeric values.
[Example 1] Assign a vector with 9 elements ranging from 1 to 9 to the variable x in the MATLAB command window.
>> x = [1,2,3,4,5,6,7,8,9]
x =
1 2 3 4 5 6 7 8 9
The command window is the main interface for user interaction with MATLAB. “>>” is the prompt, where various MATLAB commands can be entered to produce corresponding results.
In Example 1, the resulting x is a row vector, which is placed within square brackets []. The values inside can be separated by commas or spaces. To obtain a column vector, the values should be separated by semicolons. The transpose operator “‘” can be used to convert between row and column vectors.
[Example 2] Generate a column vector and assign it to y and z.
>> y=[1;2;3]
y =
1 2 3
>> z=[1,2,3]'
z =
1 2 3
(2) Assigning values to vectors using the colon expression.
MATLAB defines a unique colon expression for assigning values to row vectors, with the basic usage format:
j:k is equivalent to [j,j+1,...,k] j:k is empty, if j>k
j:i:k is equivalent to [j,j+i,j+2i,...,k] j:i:k is empty, if i == 0, if i>0 and j>k, or if i<0 and j<k
[Example 3] Generate a row vector using a colon expression.
>> D = 1:4
D =
1 2 3 4
>> E = 0:.1:.5
E =
0 0.1000 0.2000 0.3000 0.4000 0.5000
(3) Assigning values to vectors using functions.
Functions such as linspace(), logspace(), zeros(), ones(), rand(), randn(), etc., can be used to generate vectors.
[Example 4] Generate a row vector using the linspace() function.
>> linspace(1,4,5)
ans =
1.0000 1.7500 2.5000 3.2500 4.0000
(4) Using a for loop to assign values to vectors.
[Example 5] Assign values to vector b using a for loop.
>> for m=1:5, b(m)=m^2;end >> b
b =
1 4 9 16 25
2. Vector Operations
Vector operations can target a specific element or several elements of a vector, or they can be performed on the entire vector as a whole for collective operations.
To operate on a specific element or several elements of a vector is straightforward, simply use parentheses () along with the element’s ordinal number in the vector. This allows for calling the value of an element, assigning a value to an element, or changing its value. It is particularly noteworthy that using end as an ordinal number conveniently allows operations on the last element of the vector, and (end-1), (end-2), etc., can be used to operate on the second-to-last, third-to-last elements, respectively.
[Example 6] Swap the 3rd element and the last element of vector b from Example 5, and display the result after swapping.
>> c=b(3);b(3)=b(end);b(end)=c; >> b
b =
1 4 25 16 9
During the process of calling element values in a vector, if the ordinal number in parentheses exceeds the number of elements in the vector, an error will occur. However, if during the process of assigning values to vector elements, if the ordinal number in parentheses exceeds the number of elements, the assignment will be completed, and zeros will be added as necessary. Please see Example 7 for specifics.
[Example 7] The situation that occurs when the ordinal number of an element exceeds the number of elements in vector b from Example 1.10.
>> b(8)??? Attempted to access b(8); index out of bounds because numel(b)=5.
>> b(8)=8
b =
1 4 25 16 9 0 0 8
>> b(8)
ans =
8
In Example 7, the error message in the second line of the code indicates the use of the numel() function, which is used to check the number of elements in a vector (or array). Similarly, there are several other functions like size(), length(), ndims(), etc., that can also be used to check information about vectors (or arrays).
3. Vectorized Computation
Many standard MATLAB functions can be “vectorized”: they can operate on entire arrays, appearing as if many identical functions are independently applied to each element of the array. For example:
>> sqrt([1,4;9,16])
ans =
1 2 3 4
>> abs([0,1,-2,5,-6,7])
ans =
0 1 2 5 6 7
Next, consider the following function:
function d = minDistance(x,y,z) % Find the min distance between a set of points and the origin
nPoints = length(x); d = zeros(nPoints,1);
for k = 1:nPoints %Calculate the distance of each point relative to the origin d(k) = sqrt(x(k)^2 + y(k)^2 + z(k)^2);
d = min(d);
For each point, its distance from the origin is calculated and stored in d, then min is used to find the shortest distance. Vectorization can also be used for distance calculations, replacing the for loop with vector operations, such as:
function d = minDistance(x,y,z)%Calculate the minimum distance of a series of points relative to the origin
d = sqrt(x.^2 + y.^2 + z.^2); %Calculate the distance of each point relative to the origin
d = min(d); %Get the minimum distance
The modified code uses vector operations to complete the distance calculations. The power operator .^ is first applied to each element of the arrays x, y, and z. Then, the sum of each element of the array is calculated before taking the square root, resulting in a distance array (a more efficient equivalent operation is d = sqrt(min(x.^2 + y.^2 + z.^2))). The first version of the minDistance program took 0.73 seconds to calculate 50,000 points, while the vectorized version took only 0.04 seconds, achieving an 18-fold speed increase. Commonly used functions for vectorization include: min(), max(), repmat(), meshgrid(), sum(), cumsum(), diff(), prod(), cumprod(), accumarray(), filter().
The above content is from “Advanced Optical Simulation (MATLAB Version) – Optical Waveguides, Lasers” (3rd Edition)