Beruflich Dokumente
Kultur Dokumente
One way to make your MATLAB programs run faster is to vectorize the algorithms you use
in constructing the programs. Where other programming languages might use for loops or DO
loops, MATLAB can use vector or matrix operations. A simple example involves creating a
table of logarithms:
x = .01;
for k = 1:1001
y(k) = log10(x);
x = x + .01;
end
x = .01:.01:10;
y = log10(x);
For more complicated code, vectorization options are not always so obvious.
repmat creates an output array that contains the elements of array A, replicated and "tiled" in
an M-by-N arrangement:
A = [1 2 3; 4 5 6];
B = repmat(A,2,3);
B =
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
1 2 3 1 2 3 1 2 3
4 5 6 4 5 6 4 5 6
repmat uses vectorization to create the indices that place elements in the output array:
function B = repmat(A, M, N)
Step 2 creates two column vectors. mind contains the integers from 1 through the row size of
A. The nind variable contains the integers from 1 through the column size of A.
Step 3 uses a MATLAB vectorization trick to replicate a single column of data through any
number of columns. The code is
B = A(:,ones(1,nCols))
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:
1. The first element of mind, the row index, is paired with each element of nind.
MATLAB moves through the nind matrix in a columnwise fashion, so mind(1,1)
goes with nind(1,1), and then nind(2,1), and so on. The result fills the first row of
the output array.
2. Moving columnwise through mind, each element is paired with the elements of nind
as above. Each complete pass through the nind matrix fills one row of the output
array.
Use the Vectorized property to specify whether to compute custom regressors using
vectorized form during estimation. If you know that your regressor formulas can be
vectorized, set Vectorized to 1 to achieve better performance. To better understand
vectorization, consider the custom regressor function handle z=@(x,y)x^2*y. x and y are
vectors and each variable is evaluated over a time grid. Therefore, z must be evaluated for
each (xi,yi) pair, and the results are concatenated to produce a z vector:
for k = 1:length(x)
z(k) = x(k)^2*y(k)
end
%result string;
fprintf('Pass\n');
else
fprintf('Fail\n');
externalmark=0;
end
fprintf('Total Marks=%0.2f',final);