多维矩阵的最大线性索引 - MATLAB

das*_*ast 5 matlab matrix matrix-indexing

假设我有一个3-dimensional矩阵并计算了max第二维,并希望得到最大值的线性指数.但是,max-function只返回一个维度的下标.

A = randn([5,5,5]);        % Generate random matrix
[M, Ind] = max(A,[],2);    % Take the max along dimension 2
Run Code Online (Sandbox Code Playgroud)

如何转移indexlinear indexing,这样

M == A(Ind)
Run Code Online (Sandbox Code Playgroud)

变成了真的?

我对这个问题的意图是,我有two multi-dimensional矩阵和需要计算maxfirst一个.然后,我想要在second矩阵中正确地访问那些我在一个中找到最大值的位置first.

Dan*_*Dan 2

一种方法是使用sub2ind

A = randn([5,5,5]);       
[M, col] = max(A,[],2);   

[m,n,o] = size(A);

dim1 = mod((0:m*o-1)', m)+1;
dim2 = col(:);
dim3 = ceil((1:m*o)/m)';

ind = sub2ind(size(A), dim1, dim2, dim3)
Run Code Online (Sandbox Code Playgroud)

验证它适用于

isequal(M(:), A(ind))
Run Code Online (Sandbox Code Playgroud)

让它们具有相同的形状M

reshape(ind, m, 1, o)
Run Code Online (Sandbox Code Playgroud)