In MATLAB programming, the process of replacing loops with vectorized statements is called vectorization.Example: Calculating the square, square root, and cube root of all integers from 1 to 100.1. Using a for loop
% Calculate the square, square root, and cube root of each integer from 1 to 100
square = zeros(1, 100); % Preallocate memory for each integer's square
square_root = zeros(1, 100); % Preallocate memory for each integer's square root
cube_root = zeros(1, 100); % Preallocate memory for each integer's cube root
for ii = 1 : 100
square(ii) = ii^2;
square_root(ii) = ii^(1 / 2);
cube_root(ii) = ii^(1 / 3);
end
The above loop executes 100 times, calculating one value for each output array during each iteration.MATLAB provides a faster alternative for this type of computation:vectorization.2. Using vectorization
% Calculate the square, square root, and cube root of each integer from 1 to 100
% Vectorized programming
ii = 1 : 100;
square = ii.^2;
square_root = ii.^(1 / 2);
cube_root = ii.^(1 / 3);
The above code uses vectorization to perform the same calculations as the loop. It first creates an array for computation, then performs the calculation on the array in a single statement, completing the calculations for all 100 elements at once.
Although both calculations yield the same results, they are not equivalent. The version with the for loop is over 15 times slower than the vectorized version! The reason is that the statements in the for loop are interpreted and executed by MATLAB during each iteration. In fact, MATLAB needs to interpret and execute 300 lines of code. In contrast, in the vectorized version, MATLAB only interprets and executes 4 lines of code. Due to MATLAB’s ability to efficiently implement vectorized statements, it is faster under this module.
If both a for loop and vectorization can be used in programming, please use vectorization to improve execution speed.
Happy learning to everyone~~