作为替代解决方案,你可以使用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