使用repmat优化matlab代码

使用repmat优化matlab代码,matlab,optimization,Matlab,Optimization,在我的代码的某些部分中,我对一个非常大的向量使用了repmat vecO=repmat(vec,1,9); fi = repmat(vecO',1,400)-A; vec是1×400矩阵,“a”是3600×400矩阵。我认为应该有一种比使用repmat更省时的方法,但我不知道该方法是什么。有人知道吗 您的问题fi中的结果似乎应该包含A的每一列的vec0差异。这意味着,您不必使用repmat通过生成400个副本将vec0扩展到与A相同的大小,而可以使用隐式扩展将元素操作应用于两个数组。使用此函数

在我的代码的某些部分中,我对一个非常大的向量使用了repmat

vecO=repmat(vec,1,9);
fi = repmat(vecO',1,400)-A;

vec是1×400矩阵,“a”是3600×400矩阵。我认为应该有一种比使用repmat更省时的方法,但我不知道该方法是什么。有人知道吗

您的问题fi中的结果似乎应该包含A的每一列的vec0差异。这意味着,您不必使用repmat通过生成400个副本将vec0扩展到与A相同的大小,而可以使用隐式扩展将元素操作应用于两个数组。使用此函数不会复制vec0,但应获得相同的结果。第一个参数指定要应用于两个数组的函数,这里它只是负号


下面是要使用的模板测试,包括:

结果

8.3.0.532 (R2014a)
Time taken with 2 repmats:    0.004027661867427

Time taken with 1 repmat and transpose:    0.004034170491803

Time taken with bsxfun:    0.003970521454027

它比使用repmat快吗?我不确定。。。值得检查我在回答中添加了这个测试,因为它是一个内置函数。那就换个名字吧。剩下的很好,谢谢。非常有趣的是,两次调用repmat比一次调用两个维度要快。@Adiel是的,这本来是我的建议。事实上,它最初是repmatvec,400,9'-A,但这需要大约3倍的时间。
vec = rand(1,400);
A = rand(3600,400);
n_expts = 1000;
format long
disp(version);

% Warm up
for ii = 1:n_expts
    vec0 = repmat(vec,1,9);
    res1 = repmat(vec0',1,400)-A;
    res3 = bsxfun(@minus, vec0.', A);
end

tic
for ii = 1:n_expts
    vec0 = repmat(vec, 1, 9);
    res1 = repmat(vec0.', 1, 400) - A;
end
fprintf('Time taken with 2 repmats: ')
disp(toc/n_expts)

tic
for ii = 1:n_expts
    res2 = repmat(vec.', 9, 400) - A;
end
fprintf('Time taken with 1 repmat and transpose: ')
disp(toc/n_expts)

tic
for ii = 1:n_expts
    res3 = bsxfun(@minus, vec0.', A);
end
fprintf('Time taken with bsxfun: ')
disp(toc/n_expts)

% Check that all the fi are the same
dres1 = max(max(abs(res1 - res2)));
dres2 = max(max(abs(res1 - res3)));
tol = eps;
if (dres1 > eps) | (dres2 > eps)
    fprintf('Difference in output matrices');
end
8.3.0.532 (R2014a)
Time taken with 2 repmats:    0.004027661867427

Time taken with 1 repmat and transpose:    0.004034170491803

Time taken with bsxfun:    0.003970521454027