fork download
  1. t=zeros(1,4);
  2. n=10000; % size of matrices
  3. it=2; % average results over XX trails
  4. for ii=1:it,
  5. % random inputs
  6. A=rand(n);
  7. B=rand(n);
  8. % John's rejected solution
  9. tic;
  10. n1=sum(diag(A*B'));
  11. t(1)=t(1)+toc;
  12. % element-wise solution
  13. tic;
  14. n2=sum(sum(A.*B));
  15. t(2)=t(2)+toc;
  16. % MOST efficient solution - using vector product
  17. tic;
  18. n3=A(:)'*B(:);
  19. t(3)=t(3)+toc;
  20. % using trace
  21. tic;
  22. n4=trace(A*B');
  23. t(4)=t(4)+toc;
  24. % make sure everything is correct
  25. assert(abs(n1-n2)<1e-8 && abs(n3-n4)<1e-8 && abs(n1-n4)<1e-8);
  26. end;
  27. t./it
Success #stdin #stdout #stderr 3.33s 2126060KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
/bin/bash: line 2: 2464173 Killed                  TMP="$TMPDIR" octave -q --no-window-system --no-history /home/UWHvAM/prog.octave > a.out