我正在编写一个代码,其中速度和时间的减少非常重要。我必须通过重复一些向量来创建一些矩阵。由于我的向量几乎很大,使用repmat创建这些矩阵需要相当长的时间。还有其他方法可以缩短这段时间吗?
答案 0 :(得分:4)
我们的测试载体:
V0 = [1; 2; 3];
Tony的伎俩:
V1 = V0(:, ones(3,1))
矩阵/向量乘法:
V2 = V0 * ones(1,3);
Kronecker产品:
V3 = kron(V0, ones(1,3))
连接:
V4 = [V0 V0 V0]
不明白的方式:
V5 = arrayfun(@(~)V0, 1:3, 'uniformoutput', false);
V5 = cat(2, V5{:});
最不明显的方式:
[Vi{1:3}] = deal(V0);
V6 = [Vi{:}]
使用Lightspeed toolbox中的repmat
。
或者,最好的方法是使用隐式扩展(R2008及以上版本):
%# NOTE: this PREVENTS having to do explicit replication, and carries
%# out the multiplication re-using the same elements from V0:
M = bsxfun(@times, rand(1,5), V0)