% This is a script file to illustrate loops and % MATLAB's built-in vectorization % clc disp(' Loops and Vectorization') disp(' ') disp('Note: AVOID LOOPS WHENEVER POSSIBLE (perhaps not so much in MATLAB 7)') disp('As a first example we compute the square of the length (or 2-norm) of a random vector:') n = input('Enter length of vector [enter=50000]: '); if isempty(n) n = 50000; end x = rand(n,1); disp('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) disp('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) disp('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)