Page 50 - Applied Numerical Methods Using MATLAB
P. 50
TOWARD GOOD PROGRAM 39
can run them to find that one works fine, while the other gives a quite wrong
result. Could you tell which one is better?
1.3.2 Vector Operation Versus Loop Iteration
It is time-efficient to use vector operations rather than loop iterations to perform a
repetitive job for an array of data. The following program “nm132_1.m” compares
a vector operation versus a loop iteration in terms of the execution speed. Could
you tell which one is faster?
%nm132_1: vector operation vs. loop iteration
N = 100000; th = [0:N-1]/50000*pi;
tic
ss=sin(th(1));
for i = 2:N, ss = ss + sin(th(i)); end % loop iteration
toc, ss
tic
ss = sum(sin(th)); % vector operation
toc, ss
As a more practical example, let us consider a problem of finding the DtFT
(discrete-time Fourier transform) ([W-3]) of a given sequence x[n].
N−1
−j n
X( ) = x[n]e for = [−100 : 100]π/100 (1.3.4)
n=0
The following program “nm132_2.m” compares a vector operation versus a loop
iteration for computing the DtFT in terms of the execution speed. Could you tell
which one is faster?
%nm132_2: nested structure
N = 1000; x = rand(1,N); % a random sequence x[n] for n = 0:N-1
W = [-100:100]*pi/100; % frequency range
tic
for k = 1:length(W)
X1(k) = 0; %for for loop
for n = 1:N, X1(k) = X1(k) + x(n)*exp(-j*W(k)*(n-1)); end
end
toc
tic
X2=0;
for n = 1:N %for vector loop
X2 = X2 +x(n)*exp(-j*W*(n-1));
end
toc
discrepancy = norm(X1-X2) %transpose for dimension compatibility