(Matlab)使用min函数返回的索引进行维度索引 [英] (Matlab) Dimensional indexing using indices returned by min function

查看:435
本文介绍了(Matlab)使用min函数返回的索引进行维度索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个5维矩阵C.我使用下面的代码得到一个min矩阵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(第一列)。 / p>

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

解决方案

将此用于5D矩阵 -

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

编辑1:这是针对您不是在寻找全局但特定维度的最小值和索引的情况。



代码

  %% //演示的随机数据
C = randi(60,2,3,4,2,3);

%% //你的方法
[C1,I1] = min(C,[],1)
[C2,I2] = min(C1,[], 2)
[C3,I3] = min(C2,[],3)

%% //我的方法
dimID = 3; %% //尺寸,直到找到最小值
C_size = size(C);
dim_v1 = prod(C_size(1:dimID))
dim_v2 = prod(C_size(1:dimID-1))

t1 =重塑(C,[dim_v1 C_size( dimID + 1:end)])
[val,ind1] = min(t1,[],1)
chk1_ind = ceil(ind1 / dim_v2)

%% / /这可能就足够了,但是你坚持要获得格式为
%% //的索引与从你的方法获得的索引相同,请尝试下一步

C_size(1: dimID)= 1;
chk2_ind = reshape(chk1_ind,C_size)

%% //验证
error_check = isequal(chk2_ind,I3)


Suppose I have a 5-d matrix C. I use the following code to get a min matrix C3 (each element of C3 represents the minimum of dimension 1,2,3):

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

The question is how to get the index of the minimum in terms of each dimension? For example consider this simpler case:

C = [1,2;3,4]

The minimum here is 1, its index in dimension 1 is 1 (first row) and in dimension 2 also 1 (first column).

I know that changing the sequence of these expressions would give me the right answer, but what if I want to get all dimensional indices with computing these expressions only once?

解决方案

Use this for a 5D matrix -

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

Edit 1: This is for a case where you are not exactly looking for global but dimension specific minimum values and indices.

Code

%%// 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)

这篇关于(Matlab)使用min函数返回的索引进行维度索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆