具體尺寸例
如果你不關心的通用解決方案,爲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
,但A
是4D
數組,然後做 -
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
這麼一般性,呵呵!
這似乎工作,雖然不能說速度/透明度。謝謝一堆! –