|Programming and Data Types|
MATLAB is a matrix language, which means it is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. Vectorization means converting
while loops to equivalent vector or matrix operations.
|Note Before taking the time to vectorize your code, read the section on Performance Acceleration. You may be able to speed up your program by just as much using the MATLAB JIT Accelerator instead of vectorizing.|
A Simple Example
Here is one way to compute the sine of 1001 values ranging from 0 to 10.
A vectorized version of the same code is:
The second example executes much faster than the first and is the way MATLAB is meant to be used. Test this on your system by creating M-file scripts that contain the code shown, then using the
toc functions to time the M-files.
An Advanced Example
repmat is an example of a function that takes advantage of vectorization. It accepts three input arguments: an array
A, a row dimension
M, and a column dimension
repmat creates an output array that contains the elements of array
A, replicated and "tiled" in an
repmat uses vectorization to create the indices that place elements in the output array.
function B = repmat(A,M,N) if nargin < 2 error('Requires at least 2 inputs.') elseif nargin == 2 N = M; end % Step 1 Get row and column sizes [m,n] = size(A); % Step 2 Generate vectors of indices from 1 to row/column size mind = (1:m)'; nind = (1:n)'; % Step 3 Creates index matrices from vectors above mind = mind(:,ones(1,M)); nind = nind(:,ones(1,N)); % Step 4 Create output array B = A(mind,nind);
Step 1, above, obtains the row and column sizes of the input array.
Step 2 creates two column vectors.
mind contains the integers from 1 through the row size of
nind variable contains the integers from 1 through the column size of
Step 3 uses a MATLAB vectorization trick to replicate a single column of data through any number of columns. The code is
n_cols is the desired number of columns in the resulting matrix.
Step 4 uses array indexing to create the output array. Each element of the row index array,
mind, is paired with each element of the column index array,
nind, using the following procedure:
mind, the row index, is paired with each element of
nind. MATLAB moves through the
nindmatrix in a columnwise fashion, so
nind(2,1), and so on. The result fills the first row of the output array.
mind, each element is paired with the elements of
nindas above. Each complete pass through the
nindmatrix fills one row of the output array.
Functions Used in Vectorizing
Some of the most commonly used functions for vectorizing are
|Techniques for Improving Performance||Preallocating Arrays|