做这样的事情:
(1:10)' * (1:10)
编辑--->
当 N 很大时,我测试了 Daniel、我、Luis Mendo 和 David 建议的解决方案的速度:
N = 100; % number of iterations
runtime_a = zeros(N, 1); % runtime of Daniel's solution
runtime_b = zeros(N, 1); % runtime of the obvious solution
runtime_c = zeros(N, 1); % runtime of Luis Mendo's solution
runtime_d = zeros(N, 1); % runtime of Luis Mendo's solution
runtime_e = zeros(N, 1); % runtime of David's solution
n = 5000; % number of elements
one_to_n = 1:n;
for hh = 1:N
% Solution by Daniel R.
tic, a = bsxfun(@times, one_to_n, one_to_n'); runtime_a(hh) = toc;
clear a
tic, b = one_to_n' * one_to_n; runtime_b(hh) = toc;
clear b
% Solution by Luis Mendo
tic, c = cell2mat(arrayfun(@(x) (x:x:n*x).', one_to_n, 'uni', false)); runtime_c(hh) = toc;
clear c
% Solution by Luis Mendo.
tic, d = cumsum(repmat(one_to_n, [n 1])); runtime_d(hh) = toc;
clear d
% Solution by David
tic, [A, B] = meshgrid(one_to_n); e = A.*B; runtime_e(hh) = toc;
clear e
end
% Check mean and standard deviation:
mean([runtime_a, runtime_b, runtime_c, runtime_d, runtime_e])
std([runtime_a, runtime_b, runtime_c, runtime_d, runtime_e])
结果是:
% mean:
0.105048900691251 0.188570704057917 0.491929288458701 0.787045026437718 0.979624197407329
% standard deviation:
0.034274873626281 0.077388368324427 0.163983982925543 0.285395301735065 0.372693172505310
因此,显然,当 N 很大时,Daniel 的解决方案是最快的。