从 Matrix 3D 中获取 Matrix 2D,其中给定的第三维对应于第一维

Get Matrix 2D from Matrix 3D with a given choice of the third dimension corresponding to the first dimension

我有:

我需要捕获二维矩阵 B (m,n),其中 A 的第三维取自相应的选项。例如:

idn(1) = 1;
idn(2) = k;
idn(j) = k-1;

然后:

B(1,:) = A(1,:,idn(1)) = A(1,:,1);
B(2,:) = A(2,:,idn(2)) = A(2,:,k);
B(j,:) = A(j,:,idn(j)) = A(j,:,k-1);

由于 idn 不是固定的,简单的 squeeze 也无济于事。

我也试过下面的代码,但是也不行。

B = A(:,:,idn(:));

如果有人能给我一个解决方案,我将不胜感激。

这可以通过 sub2ind and permute, but the simplest way I can think of is using linear indexing 手动完成:

A = rand(3, 4, 5); % example data
idn = [5; 1; 2];   % example data
ind = (1:size(A,1)).' + size(A,1)*size(A,2)*(idn(:)-1); % 1st and 3rd dimensions
ind = ind + size(A,1)*(0:size(A,2)-1); % include 2nd dimension using implicit expansion
B = A(ind); % index into A to get result