%% Loops and Vectorization I %% % Note: *Avoid loops whenever possible* (even though the latest versions of % MATLAB now optimize loops and are much more efficient than they used to be) % % As a first example we compute the square of the length (or 2-norm) of a % random vector: % % Define the length of vector n = 50000; %% % Define a random vector x = rand(n,1); %% % How long does a for-loop take? tic; s = 0; for i=1:n s = s + x(i)^2; end t1 = toc; fprintf('norm(x) = %f \n', s) fprintf('Time with for-loop: %f seconds\n\n', t1) %% % Now vectorized using MATLAB's sum function tic; s = sum(x.^2); t2 = toc; fprintf('norm(x) = %f \n', s) fprintf('Time vectorized with sum: %f seconds\n\n', t2) %% % And using MATLAB's norm function tic; s = norm(x)^2; t3 = toc; fprintf('norm(x) = %f \n', s) fprintf('Time vectorized with norm: %f seconds\n\n', t3)