数组中最大值和最小值的索引

时间:2022-09-27 08:36:45

How can I find the index of the maximum element in an array without looping?

如何在不使用循环的情况下找到数组中最大元素的索引?

For example, if I have:

例如,如果我有:

a = [1 2 999 3];

I want to define a function indexMax so that indexMax(a) would return 3.

我想定义一个函数indexMax,这样indexMax(a)会返回3。

Likewise for defining indexMin.

定义indexMin同样。

3 个解决方案

#1


21  

As pointed by Evgeni max and min can return the argmax and argmin as second arguments.
It is worth while noting that you can use these functions along specific dimensions:

如Evgeni max和min所指出的,可以返回argmax和argmin作为第二个参数。值得注意的是,您可以沿着特定的维度使用这些功能:

 A = rand(4); % 4x4 matrix [ row_max row_argmax ] = max( A, [], 2 ); % max for each row - 2nd dimension [ col_min col_argmin ] = min( A, [], 1 ); % min for each column - 1st dimension

Note the empty [] second argument - it is crucial max( A, [], 2 ) is not at all equivalent to max( A, 2 ) (I'll leave it to you as a small exercise to see what max( A, 2 ) does).

注意这个空的[]第二个参数——max(A,[], 2)根本不等于max(A, 2)(我把它留给你作为一个小练习,看看max(A, 2)做什么)。

The argmax/argmin returned from these "along dimension" calls are row/col indices.

这些“沿着维度”调用返回的argmax/argmin是行/col索引。

#2


25  

The built-in max function has this functionality when two output arguments are specified:

当指定两个输出参数时,内置的max函数具有以下功能:

a = [1 2 999 3];[the_max, index_of_max] = max(a)the_max =   999index_of_max =     3

Likewise for min.

同样,分钟。

#3


7  

Just as an alternative solution, you might try this:

作为一种替代方案,您可以尝试以下方法:

a = rand(1,1000);min_idx = find(a == min(a));

Obviously, the same procedure is applicable in the case of max.

显然,同样的程序也适用于max。

I hope this helps.

我希望这可以帮助。

#1


21  

As pointed by Evgeni max and min can return the argmax and argmin as second arguments.
It is worth while noting that you can use these functions along specific dimensions:

如Evgeni max和min所指出的,可以返回argmax和argmin作为第二个参数。值得注意的是,您可以沿着特定的维度使用这些功能:

 A = rand(4); % 4x4 matrix [ row_max row_argmax ] = max( A, [], 2 ); % max for each row - 2nd dimension [ col_min col_argmin ] = min( A, [], 1 ); % min for each column - 1st dimension

Note the empty [] second argument - it is crucial max( A, [], 2 ) is not at all equivalent to max( A, 2 ) (I'll leave it to you as a small exercise to see what max( A, 2 ) does).

注意这个空的[]第二个参数——max(A,[], 2)根本不等于max(A, 2)(我把它留给你作为一个小练习,看看max(A, 2)做什么)。

The argmax/argmin returned from these "along dimension" calls are row/col indices.

这些“沿着维度”调用返回的argmax/argmin是行/col索引。

#2


25  

The built-in max function has this functionality when two output arguments are specified:

当指定两个输出参数时,内置的max函数具有以下功能:

a = [1 2 999 3];[the_max, index_of_max] = max(a)the_max =   999index_of_max =     3

Likewise for min.

同样,分钟。

#3


7  

Just as an alternative solution, you might try this:

作为一种替代方案,您可以尝试以下方法:

a = rand(1,1000);min_idx = find(a == min(a));

Obviously, the same procedure is applicable in the case of max.

显然,同样的程序也适用于max。

I hope this helps.

我希望这可以帮助。