简体   繁体   English

在Matlab中找到三维数组最小值的位置

[英]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. 很抱歉提出这么简单愚蠢的问题,但Matlab真的太难用了。 My question is just how to find the position the minimal value of a three dimensional array in Matlab. 我的问题是如何在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) . m的最小值应为-2 ,位于(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 . 而不是返回x=1y=2z=2 ,它返回x=1y=4z=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. 您可以使用min来查找m的最小索引,然后将其转换为xyz坐标。 There is no need to use find also. 没有必要使用find

min can be used with multiple output arguments to return the index of the minimum element. min可以与多个输出参数一起使用,以返回最小元素的索引。 Here, I also use : to return every element of m as a column vector. 在这里,我还使用:m每个元素作为列向量返回。

>> 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. 现在我们需要将索引转换回xyz坐标。 This can be done using ind2sub or manually by hand. 这可以使用ind2sub或手动手动完成。

>> [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. 问题是MATLAB硬连线使用矩阵(即等级2的数组),而不是一般等级的数组。 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. 如果您键入help find ,您可能会注意到您的原始代码使用了find[rows, cols, vals]版本,这不是您所期望的。

Instead, min(m(:)) is a simplification of your min(min(min(m))) . 相反, min(m(:))是你的min(min(min(m)))的简化。 It automatically reshapes m into a rank one array (ie a vector). 它自动将m重塑为一级数组(即向量)。

The expression find(m(:) == m0) returns a single index for the minimum position in this reshaped vector. 表达式find(m(:) == m0)返回此重新形状向量中最小位置的单个索引。 Finally, ind2sub converts this single index into a set of three indices, given the shape of m . 最后, ind2sub将此单个索引转换为一组三个索引,给定m的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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