Matlab - 用矩阵运算替换循环

时间:2014-09-26 23:01:48

标签: matlab for-loop matrix vectorization

我想用matrice操作替换for循环。我有一个关于我的代码所做的最小工作示例:

A = [1,2,3,4,5,6,7,8,9,10];
B= [5,2,3,4,5,1,4,7,4,2];
C = zeros(1,10);
n = length(A);
abMatrix = [1,-1,0;1,-2,1;0,-1,1];
for i=2:n-1
  C(i) = A(i-1:i+1) * abMatrix * B(i-1:i+1)';
end

此操作有效,但我真的想在一个矩阵运算中对所有i = [2,n-1]进行操作。如何删除for循环?

1 个答案:

答案 0 :(得分:3)

基于

diag + bsxfun的方法 -

nA = numel(A); %// Get number of elements in A
ind1 = bsxfun(@plus,[1:3]',0:nA-3); %// sliding indices
mat_mult = A(ind1)'*abMatrix*B(ind1); %// matrix multiplications of the three arrays

C(1,nA)=0 %// pre-allocate for C
C(2:end-1)=mat_mult(1:size(mat_mult,1)+1:end) %//get right values, set at right places

如果你关心代码紧凑性,这里是 -

ind1 = bsxfun(@plus,[1:3]',0:numel(A)-3)
C = [0 ; diag(A(ind1)'*abMatrix*B(ind1)) ; 0].'