朱莉娅:在数组中的列中找到最大值

pp1*_*p11 4 julia

假设我们有一个像这样定义的数组:

a=[1 2; 3 4; 5 5; 7 9; 1 2];
Run Code Online (Sandbox Code Playgroud)

在Matlab中,我们可以通过编写来找到最大值:

 [x y] = max(a)
   x =
     7     9
Run Code Online (Sandbox Code Playgroud)

在朱莉娅,我们可以使用:

  a=[1 2; 3 4; 5 5; 7 9; 1 2]
  findmax(a,1)
Run Code Online (Sandbox Code Playgroud)

返回:

 ([7 9],

  [4 9])
Run Code Online (Sandbox Code Playgroud)

但是,我感兴趣的不仅是找到两列的[7 9],还有它们在每列中的相对位置,如[4,4].当然,我可以写更多的编码行,但是我可以直接使用findmax吗?

Mat*_* B. 7

返回的第二个矩阵findmax是整个阵列上最大值位置的线性索引.你想要每列中的位置; 为此,您可以将线性索引转换为下标ind2sub.然后下标元组的第一个元素是你的行索引.

julia> vals, inds = findmax(a, 1)
(
[7 9],

[4 9])

julia> map(x->ind2sub(a, x), inds)
1×2 Array{Tuple{Int64,Int64},2}:
 (4,1)  (4,2)

julia> map(x->ind2sub(a, x)[1], inds)
1×2 Array{Int64,2}:
 4  4
Run Code Online (Sandbox Code Playgroud)