矢量化访问数组

时间:2016-05-30 14:57:26

标签: performance matlab vectorization

有没有办法通过矢量化来访问数组的重叠段? 或者最快的方法是什么?

带有for循环的最小样本

A=rand(5);
B=rand(10,5);
m=6;
for idx=1:m
    C(idx)=sum(sum((A(:,:)-B(idx: end-(m+1-idx),:)).^2));
end  

1 个答案:

答案 0 :(得分:0)

这是一种使用bsxfunpermute&进行矢量化访问的方法。 reshape -

% Size parameters
m = size(A,1);
n = size(B,1);

% Extended version of B, i.e. "B(idx: end-(m+1-idx)+1,:)" across all iterations
B_ext = B(bsxfun(@plus,(1:m)',0:n-m),:);

% Perform broadcasted subtraction against A and finally squared summations
C = sum(sum(bsxfun(@minus,reshape(B_ext,m,n-m+1,[]),permute(A,[1,3,2])).^2,1),3)