fork download
  1. clear all,clc
  2.  
  3. A = rand([300,300,300]); % Generate random matrix
  4. B = rand(size(A));
  5. [M, Ind] = max(A,[],2); % Take the max along dimension 2
  6. num_runs = 5;
  7.  
  8. for k = 1:50000
  9. tic(); elapsed = toc(); %// Warm up tic/toc
  10. end
  11.  
  12. tic
  13. for iter = 1:num_runs
  14. [m,n,o] = size(A);
  15.  
  16. dim1 = mod((0:m*o-1)', m)+1;
  17. dim2 = Ind(:);
  18. dim3 = ceil((1:m*o)/m)';
  19.  
  20. ind = sub2ind(size(A), dim1, dim2, dim3);
  21. end
  22. toc
  23. clear dim1 dim2 ind dim3 m n o
  24.  
  25. tic
  26. for iter = 1:num_runs
  27. [n1,n2,n3] = size(A); %// Get the size of A
  28. idx = bsxfun(@plus,bsxfun(@plus,squeeze((Ind-1)*n1),[0:n3-1]*n1*n2),[1:n1]');
  29. idx = idx(:);
  30. end
  31. toc
  32. clear idx n1 n2 n3
  33.  
  34. tic
  35. for iter = 1:num_runs
  36. [m, n, p] = size(A);
  37. [M, Ind] = max(A,[],2);
  38. LinInd = bsxfun(@plus, (1:m).', (0:p-1)*m*n); %'//
  39. LinInd = LinInd(:) + (Ind(:)-1)*m;
  40. end
  41. toc
Success #stdin #stdout 4.59s 65088KB
stdin
Standard input is empty
stdout
Elapsed time is 0.116373 seconds.
Elapsed time is 0.017565 seconds.
Elapsed time is 0.513759 seconds.