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

조회 수: 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!