(Matlab) Dimensional indexing using indices returned by min function

99封情书 提交于 2020-01-06 02:18:32

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/23321638/matlab-dimensional-indexing-using-indices-returned-by-min-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!