5

假设我有一个3-dimensional矩阵并且已经计算了max沿第二维的,并且想要获得最大值的线性索引。但是,max-functiononly 返回沿一维的下标。

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

我如何转移indexlinear indexing,这样

M == A(Ind)

变成真的?

我对这个问题的意图是我有two multi-dimensional矩阵并且需要计算其中的max矩阵first。然后,我想在second矩阵中找到最大值的位置访问矩阵中的值first

4

4 回答 4

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)

验证它适用于

isequal(M(:), A(ind))

使它们具有与以下相同的形状M

reshape(ind, m, 1, o)
于 2014-10-29T15:31:07.977 回答
1

为其他维度创建索引。

在昏暗 1 中,索引需要以最快的速度变化:[1,2,...,size(A,1)]而这size(A,3)一次:

idx1 = repmat((1:size(A,1))',size(A,3),1);

在昏暗 2 中,索引由 给出Ind

在昏暗 3 中,索引需要变化最慢:[1,1,...,1]对于size(A,1)时间,然后[2,2,...,2]依此类推,直到size(A,3).

idx3 = ones(size(A,1),1)*(1:size(A,3));

访问单个值:

 M_ = A(sub2ind(size(A),idx1(:),Ind(:),idx3(:)));

相比:

M(:) == M_
于 2014-10-29T15:58:17.487 回答
1

3维案例

[m, n, p] = size(A);
[M, Ind] = max(A,[],2);
LinInd = bsxfun(@plus, (1:m).', (0:p-1)*m*n); %'//
LinInd = LinInd(:) + (Ind(:)-1)*m;

所需的线性指数是LinInd。这产生

A(LinInd) == M(:)

包含所有true条目(请注意您需要(:)在右侧,以便比较有意义)。

一般多维情况

d = 3; %// dimension along which max will be computed
s = size(A);
sLow = prod(s(1:d-1));
sHigh = prod(s(d+1:end));
[M, Ind] = max(A,[],d);
LinInd = bsxfun(@plus, (1:sLow).', (0:sHigh-1)*sLow*s(d)); %'//
LinInd = LinInd(:) + (Ind(:)-1)*sLow;
于 2014-10-29T23:49:52.010 回答
0

让我们假设AB是您拥有的两个矩阵,您需要从中获取max索引A并使用这些索引来索引B以获得所需的输出。实现相同目标的一种方法可能是这样的 -

%// Your code to get Ind
A = randn([5,5,5]);        % Generate random matrix
[M, Ind] = max(A,[],2);    % Take the max along dimension 2

%// ------- Solution code -------------

%// Get the size of A
[n1,n2,n3] = size(A)

%// Linear indices corresponding to column and third dimension indices
col_dim3_lin_idx = bsxfun(@plus,(Ind-1)*n1,permute([0:n3-1]*n1*n2,[1 3 2]))

%// Finally get the overall linear indices
linear_index = bsxfun(@plus,col_dim3_lin_idx,[1:n1]') %//'

%// Get the corresponding elements from B
out = B(linear_index)

将所需的线性索引作为 2D 数组的方式略有不同,如下所示 -

[n1,n2,n3] = size(A) %// Get the size of A
idx = bsxfun(@plus,bsxfun(@plus,squeeze((Ind-1)*n1),[0:n3-1]*n1*n2),[1:n1]')

idx(:)将是使用这种新方法的线性索引的列向量,您可以将其索引到BieB(idx(:))以将所需的输出作为列向量。

于 2014-10-29T15:30:21.863 回答