[英]Matlab: subtract vectors in a 3D array by a list of vectors
I have n groups, each group has m vectors of dimension d. 我有n组,每组有m个维数为d的向量。 These are represented by ad*m*n matrix A.
这些由ad * m * n矩阵A表示。
I have n vectors of dimension d, represented by ad*n matrix B. 我有n个维数为d的向量,由ad * n矩阵B表示。
Now I would like to subtract all the m vectors in the group i by the corresponding vector i in B (and I do that for all i = 1,...,n). 现在我想通过B中相应的向量i减去组i中的所有m个向量(我对所有i = 1,...,n都这样做)。
This can be done simply like: 这可以简单地完成:
C = zeros(size(A));
for i = 1:n
for j = 1:m
C(:,j,i) = A(:,j,i) - B(:,i);
end
end
However, this is quite slow because of the loop. 但是,由于循环,这非常慢。 Could anybody please suggest me a very fast way to do that?
有人可以建议我这么快的方法吗?
Thank you in advance for your help. 预先感谢您的帮助。
bsxfun
完美案例 -
C = bsxfun(@minus,A,permute(B,[1 3 2]))
Give this a shot: 试一试:
B = repmat(reshape(B,[d 1 n]),[1 m 1]);
C = A - B;
EDIT 编辑
Divakar's solution is faster. Divakar的解决方案更快。 For 100 runs with d=50;m=75;n=100;
对于100次运行,d = 50; m = 75; n = 100; the average times were as follows:
平均时间如下:
Nesbit's - .0165s Nesbit的 - .0165s
Divakar's - .0013s 迪瓦卡的 - .0013s
Mine - .0023s 我的 - .0023s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.