我想用矩阵运算代替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循环?

最佳答案

基于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].'

07-26 04:24