2014-09-26 81 views
4

我想用matrice操作代替for循環。我有我的代碼做什麼的最小工作示例:Matlab - 用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循環?

+0

只是好奇:爲什麼downvote? – 2014-09-26 23:10:46

回答

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].' 
+0

哇!只有兩條線,沒有循環! – 2014-09-26 23:32:51