做這樣的事情:
(1:10)' * (1:10)
編輯--->
我已經測試解決方案由丹尼爾建議的速度,我,路易斯門多和大衛,當N很大時:
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的解決方案是最快的。
在你的榜樣,你不需要使用元素逐個元素相乘作爲由向量乘以標量。 '1 * oneten'將給出與'1. * oneten'相同的輸出。 – David
'使用元素功能'不是很清楚。如果您的答案需要包含元素操作,則可以通過乘以'。* 1'來簡單地結束您的解決方案。如果你只被允許使用元素操作,那麼丹尼爾的第二個解決方案可能是最好的。 –
我會像francesco一樣回答,因爲向量外積可以說是解決這個任務的最自然的方式,但是Daniel的解決方案似乎更快一些:'bsxfun(@times,one_to_n,one_to_n')'。也給丹尼爾的榮譽。 – chappjc