作爲替代解決方案,你可以使用repmat
完成你已經有:
b = [0, 100; -10, 1; 0, 1; -1, 1; 10, 20].';
rng = b(2, :) - b(1, :);
ofst = b(1, :);
A = round(rand(100,5) .* repmat(rng, 100, 1) + repmat(ofst, 100, 1));
你不必定義rng
或ofst
,這可以簡單地寫爲:
A = round(rand(10,5) .* repmat(diff(b), 10, 1) + repmat(b(1,:), 10, 1));
出於好奇,我寫這個問答uick基準*與Ander的bsxfun
方法進行比較。看起來bsxfun
有一些初始開銷,這意味着對於5列(自己測試其他情況)和少於幾千行,repmat
更快。在此之上,通過repmat
創建更多大型陣列可能會導致速度放慢,而我們看到bsxfun
速度更快。
對於未來的讀者,如果這並不適用於你:與broadcasting introduced from R2016b你會發現你可以使用bsxfun
和repmat
完全閃避。
*基準代碼。在Windows 64位R2015b上測試,您的里程可能會有所不同。
function benchie()
b = [0, 100; -10, 1; 0, 1; -1, 1; 10, 20].';
Tb = [];
Tr = [];
K = 20;
for k = 1:K
n = 2^k;
fb = @()bsxfunMethod(b,n);
fr = @()repmatMethod(b,n);
Tb(end+1) = timeit(fb);
Tr(end+1) = timeit(fr);
end
figure; plot(2.^(1:K), Tb, 2.^(1:K), Tr); legend('bsxfun', 'repmat');
end
function bsxfunMethod(b, n)
round(bsxfun(@minus,bsxfun(@times, rand(n,5), diff(b)), b(1,:)));
end
function repmatMethod(b, n)
round(rand(n,5) .* repmat(diff(b), n, 1) + repmat(b(1,:), n, 1));
end
使用`range`作爲變量名,因爲它是一個[函數名](http://www.mathworks.com/help/stats/range.html?s_tid=doc_ta)
避免更改var名稱後,同樣的錯誤Persis – EBH
@EBH即使 – OBX
這不是錯誤的原因,只是一個好習慣。 – EBH