【问题标题】:MATLAB pairwise differences in Nth dimension第 N 维的 MATLAB 成对差异
【发布时间】:2015-10-14 19:06:07
【问题描述】:

假设我有一个可以是任意大小的 N 维矩阵A。例如:

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

我想沿给定维度计算矩阵元素之间所有可能的成对差异。例如,如果我想计算沿维度 3 的差异,一个捷径是创建一个矩阵,如下所示:

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

但是,我希望它能够在任何维度上使用任何大小的矩阵进行操作。因此,理想情况下,我想创建一个函数,该函数接受矩阵A 并计算沿维度DIM 的所有成对差异,或者找到一个执行相同操作的内置 MATLAB 函数。

diff 函数似乎很有用,但它只计算相邻元素之间的差异,而不是所有可能的差异。

在对这个问题进行研究时,我发现了 coupleposts 关于获得所有可能的差异,但其中大部分是针对向量中的项目(并忽略维度问题)。有人知道快速修复吗?

【问题讨论】:

    标签: arrays matlab matrix difference dimension


    【解决方案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的情况,看来你需要欢迎reshapespermutes的聚会-

    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
    

    这么多的概括,呵​​呵!

    【讨论】:

    • 这似乎可行,但不能代表速度/透明度。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 2018-05-10
    • 1970-01-01
    • 2019-06-30
    • 2011-11-13
    • 2020-06-10
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多