2015-10-14 28 views
1

假設我有一個N維矩陣A可以是任何大小。例如:MATLAB在第N維方面的成對差異

A = rand([2,5,3]); 

我想計算矩陣元素之間沿給定維度的所有可能的成對差異。例如,如果我想計算沿3維的差異,一個快捷方式是創建像這樣一個矩陣:

B = cat(3, A(:,:,2) - A(:,:,1), A(:,:,3) - A(:,:,1), A(:,:,3) - A(:,:,2)); 

不過,我想這是能夠沿着任何維度進行操作,以矩陣任何尺寸。所以,理想情況下,我想要創建一個函數,它將採用矩陣A並計算沿着維度​​的所有成對差異,或者找到內置的MATLAB函數來執行相同的操作。

diff功能似乎可能是有用的,但它只計算相鄰元素之間的差異,並非所有可能的差異。

做了我對這個問題的研究,我發現coupleposts關於獲得所有可能的差異,但其中大部分是針對向量中的項目(並忽略維度問題)。有誰知道一個快速修復?

回答

1

具體尺寸例

如果你不關心的通用解決方案,爲dim=3情況下,這將是作爲代碼幾行簡單 -

dim = 3 
idx = fliplr(nchoosek(1:size(A,dim),2)) 
B = A(:,:,idx(:,1)) - A(:,:,idx(:,2)) 

可以移動圍繞那些idx(..)到特定的維度位置,如果你碰巧知道這個維度。所以,讓我們說dim = 4,然後就去做 -

B = A(:,:,:,idx(:,1)) - A(:,:,:,idx(:,2)) 

還是讓我們說dim = 3,但A4D數組,然後做 -

B = A(:,:,idx(:,1),:) - A(:,:,idx(:,2),:) 

通用案例

對於Nth dim的情況,似乎您需要歡迎派對and permutes -

function out = pairwise_diff(A,dim) 

%// New permuting dimensions 
new_permute = [dim setdiff(1:ndims(A),dim)]; 

%// Permuted A and its 2D reshaped version 
A_perm = permute(A,new_permute); 
A_perm_2d = reshape(A_perm,size(A,dim),[]); 

%// Get pairiwse indices for that dimension 
N = size(A,dim); 
[Y,X] = find(bsxfun(@gt,[1:N]',[1:N])); %//' OR fliplr(nchoosek(1:size(A,dim),2)) 

%// Get size of new permuted array that would have the length of 
%// first dimension equal to number of such pairwise combinations 
sz_A_perm = size(A_perm); 
sz_A_perm(1) = numel(Y); 

%// Get the paiwise differences; reshape to a multidimensiona array of same 
%// number of dimensions as the input array 
diff_mat = reshape(A_perm_2d(Y,:) - A_perm_2d(X,:),sz_A_perm); 

%// Permute back to original dimension sequence as the final output 
[~,return_permute] = sort(new_permute); 
out = permute(diff_mat,return_permute); 

return 

這麼一般性,呵呵!

+0

這似乎工作,雖然不能說速度/透明度。謝謝一堆! –