具体尺寸案例
如果您不关心通用解决方案,对于 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的情况,看来你需要欢迎reshapes和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
这么多的概括,呵呵!