Advertisement
celestialgod

Reassign with index

May 28th, 2015
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.85 KB | None | 0 0
  1. clc
  2. clear
  3. mat_size = 15000;
  4. idx_length = 1e4;
  5. replications = 5;
  6. execute_time = zeros(replications, 6);
  7.  
  8. for k = 1:replications
  9.     A = randn(mat_size, mat_size);
  10.     B = rand(mat_size, mat_size);
  11.     idx = randi(mat_size, idx_length, 1);
  12.  
  13. %% method 1
  14.     t = tic;
  15.     for i = 2:length(idx)
  16.         A(idx(i), idx(1:i-1)) = B(idx(i), idx(1:i-1));
  17.     end
  18.     execute_time(k, 1) = toc(t);
  19.  
  20. %% method 2
  21.     t = tic;
  22.     idx2 = arrayfun(@(x) sub2ind(size(A), idx(x)*ones(x-1, 1), idx(1:x-1)), 2:length(idx), 'UniformOutput', false);
  23.     idx2 = cat(1, idx2{:});
  24.     A(idx2) = B(idx2);
  25.     execute_time(k, 2) = toc(t);
  26.    
  27. %% method 3
  28.     t = tic;
  29.     idx3 = bsxfun(@plus, idx', (idx-1) * size(A,1));
  30.     idx3 = idx3(triu(true(length(idx), length(idx)),1));
  31.     % disp(isequal(idx3, idx2)) % 1
  32.     A(idx3) = B(idx3);
  33.     execute_time(k, 3) = toc(t);
  34.  
  35. %% method 4 (repelem is introduced in matlab 2015a)
  36.     t = tic;
  37.     tmp = repmat(1:length(idx)', 1, length(idx));
  38.     tmp = tmp(triu(true(length(idx), length(idx)), 1));
  39.     idx4 = repelem(idx(2:length(idx)), 1:length(idx)-1) + (idx(tmp)-1) * size(A, 1);
  40.     % disp(isequal(idx4, idx2)) % 1
  41.     A(idx4) = B(idx4);
  42.     execute_time(k, 4) = toc(t);
  43.    
  44. %% method 5 use mex
  45.     % mex('-v', '-largeArrayDims', 'indexAssign.cpp')
  46.     t = tic;
  47.     A2 = indexAssign(A, B, idx);
  48.     execute_time(k, 5) = toc(t);
  49.    
  50. %% method 6 use mex with inplaced modification
  51.     % mex('-v', '-largeArrayDims', 'indexAssign_inplace.cpp')
  52.     t = tic;
  53.     indexAssign_inplace(A, B, idx);
  54.     execute_time(k, 6) = toc(t);
  55.  
  56.     clear A A2 B idx idx2 idx3 idx4
  57. end
  58. disp(mean(execute_time))
  59. % matrix size method 1  method 2  method 3  method 4  method 5  method 6
  60. %        5000   1.8311    3.1876    2.2596    2.8247    1.2955    1.2534
  61. %       15000   2.2537    3.2950    2.5996    3.1878    2.2237    1.8598
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement