(Matlab)使用min函数返回的索引进行维度索引



假设我有一个5维矩阵C。我使用以下代码得到一个最小矩阵C3(C3的每个元素表示维度1,2,3的最小值):

[C1, I1] = min(C,[],1);
[C2, I2] = min(C1, [], 2);
[C3, I3] = min(C2, [], 3);

问题是如何得到每个维度的最小值的索引?例如,考虑一个更简单的情况:

C = [1,2;3,4]

这里的最小值是1,它在维度1中的索引是1(第一行),在维度2中也是1(第一列)。

我知道改变这些表达式的顺序会给我正确的答案,但如果我想通过只计算一次这些表达式来获得所有维度的索引呢?

将其用于5D矩阵-

[~,ind] = min(C(:))
[ind_dim1,ind_dim2,ind_dim3,ind_dim4,ind_dim5] = ind2sub(size(C),ind)

编辑1:这适用于这样的情况,即您并不完全在寻找全局但维度特定的最小值和索引。

代码

%%// Random data for demo
C = randi(60,2,3,4,2,3);
%%// Your method
[C1, I1] = min(C,[],1)
[C2, I2] = min(C1, [], 2)
[C3, I3] = min(C2, [], 3)
%%// My method
dimID = 3; %%// Dimension till when minimum is to be found out
C_size = size(C);
dim_v1 = prod(C_size(1:dimID))
dim_v2 = prod(C_size(1:dimID-1))
t1 = reshape(C,[dim_v1 C_size(dimID+1:end)])
[val,ind1] = min(t1,[],1)
chk1_ind = ceil(ind1/dim_v2)
%%// This might suffice for you, but you insist to get the indices in the format 
%%// identical to the one obtained from your method, try the next steps
C_size(1:dimID)=1;
chk2_ind = reshape(chk1_ind,C_size)
%%// Verify
error_check = isequal(chk2_ind,I3)

相关内容

  • 没有找到相关文章

最新更新