Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 36
1.3.2 Vector Operation vs. 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 script “nm132_1.m” compares a loop iteration and a vector operation (for computing the sum of 105 numbers) in terms of the execution speed. Could you tell which one is faster?
%nm132_1.m: Vector operation vs. Loop iteration N=1e5; th=[0:N-1]/50000*pi; tic s1=sin(th(1)); for i=2:N, s1= s1+sin(th(i)); end % Loop iteration time_loop=toc, s1 tic s2=sum(sin(th)); % Vector operation time_vector=toc, s2
As a more practical example, let us consider a problem of finding the discrete‐time Fourier transform (DtFT) [W-2 of a given sequence x[n]:
(1.3.4)
%nm132_2.m: Vector operation vs. Loop iteration N=1000; x=rand(1,N); kk=[-100:100]; W=kk*pi/100; % Frequency range % for for loop tic for k =1:length(W) X_for1(k)=0; %zeros(size(W)); for n=1:N, X_for1(k) = X_for1(k) +x(n)*exp(-j*W(k)*(n-1)); end end time_loop_loop=toc % for vector loop tic X_for2 =0 ; %zeros(size(W)); for n=1:N X_for2 = X_for2 +x(n)*exp(-j*W*(n-1)); end time_vector_loop=toc % Vector operation tic nn=[1:N].'; X_vec = x*exp(-j*(nn-1)*W); time_vector_vector=toc discrepancy1= norm(X_for1-X_vec) discrepancy2= norm(X_for2-X_vec)
The above script “nm132_2.m” compares a vector operation vs. a loop iteration for computing the DtFT in terms of the execution speed. Could you tell which one is faster?