Search code examples
arraysmatlabjuliaminimum

Returning a minimum index in an array in Julia


I am converting some code from Matlab to Julia. In the matlab code:

[~,pStar] = min(min([dPlus,dMinus],[],2))

will return the minimum element in each row and output it in column form, then return the index (row) of the minimum element in the column just like:

>> M = [1,1,1;1,1,0;1,1,1]
M =
   1   1   1
   1   1   0
   1   1   1
>> min(M,[],2)
ans =
   1
   0
   1
>> [~,row] = min(min(M,[],2))
row =  2

My question is: what would be the Julia equivalent to this? Thank you


Solution

  • indmin returns the linear index of the minimum. You can convert that to subscript form by using ind2sub, and extract the row from that:

    julia> indmin(M)
    8
    
    julia> row, col = ind2sub(M, indmin(M))
    (2, 3)
    
    julia> row
    2
    

    This approach avoids iterating twice and creating an intermediate array.

    Update: In Julia >= 0.7, this has changed to argmin, returning a CartesianIndex which you can directly use. You can also use findmin to get both minimal value and its index.