依据二维矩阵中的索引,获取三维数组中的第三维数据。
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
求助一下,目前我有一个三维数组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
我目前只能想到使用一个循环来获得,但是需要追求效率,想请问各位有更高效的方法嘛
0 Kommentare
Akzeptierte Antwort
xtemqg
am 22 Mai 2023
无非是拿 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!