通过索引一个2D矩阵和另一个2D矩阵来向量化创建3D矩阵

时间:2019-09-03 09:22:16

标签: matlab matrix optimization indexing vectorization

在下面的示例中,我通过用变量result索引a的行来创建index。我可以通过循环使其工作:

a=repmat(1:6,3,1)';
index=[1:3;2:4];

result=zeros(3,3,size(index,1));
for i=1:size(index,1)
    result(:,:,i)=a(index(i,:),:)
end

给定的aindex是:

a =
     1     1     1
     2     2     2
     3     3     3
     4     4     4
     5     5     5
     6     6     6

index =
     1     2     3
     2     3     4

输出应为:

result(:,:,1) =
     1     1     1
     2     2     2
     3     3     3

result(:,:,2) =
     2     2     2
     3     3     3
     4     4     4

在实践中,aindexn*3矩阵,其中n非常大。

a是节点坐标,index是节点的三角形面索引。

表面太大,所以我真的需要加快循环速度

我有一个想法,向量化可以使代码更快。但是,即使使用某些矩阵“调整大小”或矩阵旋转功能(例如resizereshape),我也无法获得理想的输出结果。

1 个答案:

答案 0 :(得分:3)

对于此示例(我认为是一般情况),可以结合使用reshapepermute

请注意,我已经使用了几个转置(.')操作来使reshape起作用,可能是您可以简化此操作,但这并不应该太慢:

result = permute( reshape( a(index.',:).', size(a,2), size(index,2), [] ), [2 1 3] );

如果您的问题中隐含着size(a,2) = size(index,2) = 3,那么您当然可以将其简化(但不太笼统):

result = permute( reshape( a(index.',:).', 3, 3, [] ), [2 1 3] );

打破这一点,

a(index.',:).'          % Gives the 2D results
reshape( ..., size(a,2), size(index,2), [] ) % Convert 2D to 3D, with row and column
                                             % sizes defined by 'a' and 'index'
permute( ..., [2 1 3] ) % We need another "transpose", but that isn't defined in the
                        % 3D case. Use 'permute' to swap the 1st and 2nd dimensions
相关问题