fork download
  1. clear all,clc
  2. M = 100;
  3. N = 100;
  4.  
  5. ii = randi(9,1,M);
  6. jj = randi(9,1,M);
  7.  
  8. %// Warm up tic/toc.
  9. for k = 1:50000
  10. tic(); elapsed = toc();
  11. end
  12.  
  13.  
  14. disp('-------------------- With FOR-LOOP')
  15. tic
  16. N1 = numel(ii);
  17. N2 = numel(jj);
  18. out = zeros(N1*N2,1);
  19. idx = 1;
  20. for k1 = 1:N1
  21. for k2 = 1:N2
  22. out(idx) = ii(k1) + jj(k2);
  23. idx = idx + 1;
  24. end
  25. end
  26. toc
  27. clear N1 N2 out idx k1 k2
  28.  
  29. disp('-------------------- With BROADCASTING')
  30. tic
  31. out = reshape(ii(:).' + jj(:),[],1);
  32. toc# your code goes here
Success #stdin #stdout #stderr 0.78s 65056KB
stdin
Standard input is empty
stdout
-------------------- With FOR-LOOP
Elapsed time is 0.148444 seconds.
-------------------- With BROADCASTING
Elapsed time is 0.00038299 seconds.
stderr
warning: operator +: automatic broadcasting operation applied