首页 > 解决方案 > 在matlab中转置二维矩阵的线性索引

问题描述

我想有效地转置我的二维矩阵的线性索引,并且我努力想出有效的代码来做到这一点(见下文我的次优解决方案)。如何尽可能高效地完成这项工作(RAM 无关紧要,只是速度)?

假设我们有一个二维矩阵a

a = [1:4;5:8;9:12;13:16;17:20]'

a =

     1     5     9    13    17
     2     6    10  ->14<-  18
     3    >7<   11    15    19
     4     8    12    16    20

现在我有一些索引,比如7and 14,我真的很想转置,这样7(3,2) 的索引变为12(2,3) 并且14(4,2) 变为9(2,4)。

>> a'

ans =

     1     6     11     16
     2     7    >12<    17
     3     8     13     18
     4   ->9<-   14     19
     5     10    15     20

现在,我用了一些愚蠢的东西:

tmp = zeros(size(a));
tmp([7 14])=1; %mark linear indices as '1' in the matrix
tmp=tmp'; %transpose the whole matrix
solution = find(tmp);
%then some sorting...

solution =

      9
     12

(显然,ind2sub可以简单地获取索引,然后翻转它们。我正在寻找一种更有效的解决方案,我可以直接转换索引,而不需要额外的变量)

标签: matlabmatrixindexing

解决方案


如果我正确理解你的问题,这就是你想要的:

sz = [4 5]; % size of original a
input_ind = [7 14]; % input linear indices
row_ind = mod(input_ind-1,sz(1))+1; % row indices from input linear indices
col_ind = floor((input_ind-1)/sz(1))+1; % column indices from input linear indices
output_ind = col_ind + (row_ind-1)*sz(2); % output linear indices, obtained using
    % col_ind as row indices, row_ind as column indices, and sz(2) instead of sz(1)

推荐阅读