Search code examples
matlabmatrixminimum

Get the non-zero minimum of a column and its index


I want to find the minimum value of a column of a matrix of non-negative integers, excluding 0. I know the matrix is square and only has zeros on every element of its main diagonal (i.e. a(i,i)=0 for all i).

I have tried this:

[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));

Where nbr is the size of my matrix.

However, the index that is returned is the index excluding the zero, not taking into account the ith element. For example, my first column is:

[0 9 11 5 18 13 14]'

so the code returns best_cost=5and index=3 because the 0 element is excluded. However, I would like to get index=4 as anyone would expect.

Of course just adding 1 does not have sense, as it could happen for any column and, except for the case of this first column, the minimum of the column could be above or below the diagonal.


Solution

  • Replace zeros with inf and then use min.

    A(1:size(A,1)+1:end) = inf;    %If the diagonal is to be excluded
    %if all zeros are to be excluded including non-diagonal elements, use this instead:
    %A(A==0) = inf;                %Use tolerance if you have floating point numbers
    [best_cost, index] = min(A);