Train Scholarship Blog MATLAB Week 9
Genaro Rivera
November 11, 2022
Train Scholarship
Blog MATLAB Week 9
Pre-allocating arrays
and Vectorization (saving time by creating faster codes).
Pre-allocating
Pre-allocating creates a faster code; the tic and toc
function calculate the speed of the code. The picture on the left shows code
without pre-allocating; no pre-allocation is inefficient. MATLAB runs step by
step. Here, it first creates a 1 by 1 matrix ([1]) and goes through the loop. Next,
MATLAB repeats the for loop and creates a 1 by 2 matrix ([1 2]). Afterwards, since
I specified 100 steps (1:100), MATLAB will continuously create new elements in
the matrix. MATLAB performs 3 steps when computing the for-loop function. MATLAB
finds memory for new matrices, copies and pastes the data for the new matrix,
and deletes the old matrix; this takes time. The picture on the right shows
code with pre-allocating; pre-allocating is efficient. Here, MATLAB repeats the
same process as I described when it has no pre-allocation. However, pre-allocation
involves creating a matrix with zeros with the known dimensions of the final
product. Here, I know the final matrix will be 1 by 100 because I indicated the
size in the beginning (rad = 1:100). In doing so, MATLAB creates the 1 by 100 matrix
with zeros. This saves time from having to perform the 3 steps when computing the
for-loop function. The tic and toc functions show that no pre-allocation results
in 0.001459 seconds of processing, while pre-allocating results in 0.000652
seconds of processing. Here, this seems insignificant, but further on, code adds
up and may have hour long differences. Pre-allocating results in faster code.
Vectorization
Vectorization creates a faster code compared to
pre-allocation; the tic and toc function calculate the speed of the code. The picture
on the left is missing vectorization; although pre-allocation occurs,
vectorization is more efficient. MATLAB creates the matrix with the known
dimensions and repeats the for-loop function until it ends. The picture on the
right displays vectorization. Vectorization can sometimes, not always, replace simple
for-loop functions. Vectorization creates a vector of the known dimensions and applies
multiple operations to each element (must include the period before each
operation to ensure an element-by-element operation occurs). MATLAB automatically
loops back when you give the specified increments (here I specified 1:10000 meaning
1 through 10000 in increments of 1). The tic and toc functions show that no vectorization
results in 0.008349 seconds of processing, while with vectorization results in
0.003816 seconds of processing time. Again, currently, the time difference is
insignificant, but with longer and complicated code, it becomes significant.
Compared to pre-allocation, vectorization creates a faster code.
Comments
Post a Comment