依据二维矩阵中的索引​,获取三维数组中的第​三维数据。

11 次查看(过去 30 天)
gdmgep
gdmgep 2023-5-22
回答: xtemqg 2023-5-22
求助一下,目前我有一个三维数组a=[10,10,5];同时有一个二维矩阵index,大小为(3,2),其中第一列为三维数组的第一维索引,第二列为三维数组的第二维索引,如何取出在这三个索引位置a的第三维数据,也就是得到大小为(3,5)的矩阵。
a = rand(10, 10, 5);
index = [1,2; 2,4; 5,7];
result = zeros(3,5);
for k = 1:size(index, 1)
    result(k.:) = a(index(k,1), index(k,2), :);
end
我目前只能想到使用一个循环来获得,但是需要追求效率,想请问各位有更高效的方法嘛

采纳的回答

xtemqg
xtemqg 2023-5-22
无非是拿 sub2ind 多捣鼓几下,N比较大时会比for循环快
clear; clc; close all;
N = 200;
size_a = [ 20, 20, 5 ];
a = reshape( [ 1 : 1 : prod( size_a ) ], size_a ); % a = rand(10, 10, 5);
index = randi( [ 1, size_a( 1 ) ], [ N, 2 ] ); %[1,2; 2,4; 5,7];
result = zeros( N, size_a( 3 ) );
tic;
for k = 1 : 1 : N % size( index, 1 )
    result( k, : ) = a( index( k, 1 ), index( k, 2 ), : );
end
toc;
tic;
ind = sub2ind( size_a, ...
    repmat( index( :, 1 ), [ size_a( 3 ), 1 ] ), ...
    repmat( index( :, 2 ), [ size_a( 3 ), 1 ] ), ...
    kron( [ 1 : 1 : size_a( 3 ) ].', ones( N, 1 ) ) );
Result = reshape( a( ind ), [ N, size_a( 3 ) ] );
toc;
disp( max( abs( result - Result ), [], 'all' ) )

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!