简体   繁体   中英

Find the position of the minimal value of a three dimensional array in Matlab

Sorry for asking such a simple and silly question, but Matlab is really too hard to use for me. My question is just how to find the position the minimal value of a three dimensional array in Matlab.

For example, suppose I define a three dimensional array

m=zeros(2,2,2);
m(1,2,2)=-2;

The minimal value of m should be -2 , located at (1,2,2) . I can find the minimal value by

m0=min(min(min(m)));

But when I find its position by using

[x y z]=find(m==m0);

Instead of returning x=1 , y=2 and z=2 , it returns x=1 , y=4 and z=1 .

I appreciate if anyone would answer this question!

You can use min to find the minimum index of m and then convert it to x , y and z coordinates. There is no need to use find also.

min can be used with multiple output arguments to return the index of the minimum element. Here, I also use : to return every element of m as a column vector.

>> m=zeros(2,2,2);
>> m(1,2,2)=-2;
>> m(:)
ans =
     0
     0
     0
     0
     0
     0
    -2
     0
>> [~, ind] = min(m(:))
ind =
     7

Now we have our index we need to convert it back into x , y and z coordinates. This can be done using ind2sub or manually by hand.

>> [x y z] = ind2sub(size(m), ind)
x =
     1
y =
     2
z =
     2

You're correct. This is more complicated than it should be. The problem is that MATLAB is hardwired to work with matrices (ie arrays of rank 2), rather than arrays of general rank. Here's the solution:

m0 = min(m(:))
[x y z] = ind2sub(size(m), find(m(:) == m0))

Explanation:

If you type help find , you may notice that your original code was using the [rows, cols, vals] version of find , which is not what you expected.

Instead, min(m(:)) is a simplification of your min(min(min(m))) . It automatically reshapes m into a rank one array (ie a vector).

The expression find(m(:) == m0) returns a single index for the minimum position in this reshaped vector. Finally, ind2sub converts this single index into a set of three indices, given the shape of m .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM