2015-11-22 76 views
2

現在我有N維矩陣A由p和用q N維的其它矩陣B。我想有是一個矩陣,說的C尺寸N,通過PQ這樣「克朗」產品的多維版本?

C(i,:) = kron(A(i,:), B(i,:)); 

如果N大,環比N行可能需要相當長的時間。所以目前我增強甲乙適當(組合repmat置換重塑的使用)由PQ轉N維的每個矩陣,然後通過一些配製Ç像

C = A_aug .* B_aug; 

不限更好的主意?

+1

檢查出MATLAB的FileExchange'superkron' - http://www.mathworks.com/matlabcentral/fileexchange/32578-superkron – rayryeng

回答

2

Checkout的bsxfun + permute + reshape魔法 -

out = reshape(bsxfun(@times,permute(A,[1 3 2]),B),size(A,1),[]) 

標杆&驗證

標杆碼 -

%// Setup inputs 
N = 200; 
p = 190; 
q = 180; 
A = rand(N,p); 
B = rand(N,q); 

disp('--------------------------------------- Without magic') 
tic 
C = zeros(size(A,1),size(A,2)*size(B,2)); 
for i = 1:size(A,1) 
    C(i,:) = kron(A(i,:), B(i,:)); 
end 
toc 

disp('--------------------------------------- With some magic') 
tic 
out = reshape(bsxfun(@times,permute(A,[1 3 2]),B),size(A,1),[]); 
toc 

error_val = max(abs(C(:)-out(:))) 

輸出 -

--------------------------------------- Without magic 
Elapsed time is 0.524396 seconds. 
--------------------------------------- With some magic 
Elapsed time is 0.055082 seconds. 
error_val = 
    0 
+2

謝謝,Divakar。這是一個聰明的魔法。 –