问题描述
如何在不循环的情况下找到数组中最大元素的索引?
How can I find the index of the maximum element in an array without looping?
例如,如果我有:
a = [1 2 999 3];
我想定义一个函数indexMax
,以便indexMax(a)
返回3
.
I want to define a function indexMax
so that indexMax(a)
would return 3
.
同样,用于定义indexMin
.
推荐答案
Evgeni max
和 min
可以将argmax
和argmin
作为第二个参数返回.
值得一提的是,您可以使用特定尺寸的这些功能:
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:
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
请注意第二个空的[]
参数-至关重要的是max( A, [], 2 )
根本不等于 (我将作为一个小练习,留给您看一下max( A, 2 )
确实).
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).
这些沿维度"调用返回的argmax/argmin是行/列索引.
The argmax/argmin returned from these "along dimension" calls are row/col indices.
这篇关于数组中最大值和最小值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!