在下面的示例中,我通过用变量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
给定的a
和index
是:
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
在实践中,a
和index
是n*3
矩阵,其中n
非常大。
a
是节点坐标,index
是节点的三角形面索引。
表面太大,所以我真的需要加快循环速度。
我有一个想法,向量化可以使代码更快。但是,即使使用某些矩阵“调整大小”或矩阵旋转功能(例如resize
或reshape
),我也无法获得理想的输出结果。
答案 0 :(得分:3)
对于此示例(我认为是一般情况),可以结合使用reshape
和permute
。
请注意,我已经使用了几个转置(.'
)操作来使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