%{ a script for comparison of - a vectorized approach to programming, to - loops over elements of a vector %} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the problem: how many nonzero elements there are in a given vector? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% input data: a random vector of N numbers 0-10 N=100000 v=round(10*rand(1,N)); %%% a vectorized approach: tic(); % start measuring time r = sum((v~=0)); disp(['the number of nonzeros: ' num2str(r)]); toc(); % stop measuring time and print the time interval %%% loop over elements of vector tic(); % start measuring time r=0; for k=1:length(v) if v(k)~=0 r = r+1; end end disp(['the number of nonzeros: ' num2str(r)]); toc(); % stop measuring time and print the time interval