Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- clc
- clear
- mat_size = 15000;
- idx_length = 1e4;
- replications = 5;
- execute_time = zeros(replications, 6);
- for k = 1:replications
- A = randn(mat_size, mat_size);
- B = rand(mat_size, mat_size);
- idx = randi(mat_size, idx_length, 1);
- %% method 1
- t = tic;
- for i = 2:length(idx)
- A(idx(i), idx(1:i-1)) = B(idx(i), idx(1:i-1));
- end
- execute_time(k, 1) = toc(t);
- %% method 2
- t = tic;
- idx2 = arrayfun(@(x) sub2ind(size(A), idx(x)*ones(x-1, 1), idx(1:x-1)), 2:length(idx), 'UniformOutput', false);
- idx2 = cat(1, idx2{:});
- A(idx2) = B(idx2);
- execute_time(k, 2) = toc(t);
- %% method 3
- t = tic;
- idx3 = bsxfun(@plus, idx', (idx-1) * size(A,1));
- idx3 = idx3(triu(true(length(idx), length(idx)),1));
- % disp(isequal(idx3, idx2)) % 1
- A(idx3) = B(idx3);
- execute_time(k, 3) = toc(t);
- %% method 4 (repelem is introduced in matlab 2015a)
- t = tic;
- tmp = repmat(1:length(idx)', 1, length(idx));
- tmp = tmp(triu(true(length(idx), length(idx)), 1));
- idx4 = repelem(idx(2:length(idx)), 1:length(idx)-1) + (idx(tmp)-1) * size(A, 1);
- % disp(isequal(idx4, idx2)) % 1
- A(idx4) = B(idx4);
- execute_time(k, 4) = toc(t);
- %% method 5 use mex
- % mex('-v', '-largeArrayDims', 'indexAssign.cpp')
- t = tic;
- A2 = indexAssign(A, B, idx);
- execute_time(k, 5) = toc(t);
- %% method 6 use mex with inplaced modification
- % mex('-v', '-largeArrayDims', 'indexAssign_inplace.cpp')
- t = tic;
- indexAssign_inplace(A, B, idx);
- execute_time(k, 6) = toc(t);
- clear A A2 B idx idx2 idx3 idx4
- end
- disp(mean(execute_time))
- % matrix size method 1 method 2 method 3 method 4 method 5 method 6
- % 5000 1.8311 3.1876 2.2596 2.8247 1.2955 1.2534
- % 15000 2.2537 3.2950 2.5996 3.1878 2.2237 1.8598
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement