Matlab - Replace Matrix Loop

I want to replace the for loop with matrix operations. I have a minimal working example of what my code does:

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

This operation works, but I would really like to do the operation for all i = [2, n-1] in one matrix operation. How can I remove the for-loop?

+4
source share
1 answer
An approach

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

If you care about the compactness of the code, here it is -

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

All Articles