Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active December 23, 2021 17:25
Show Gist options
  • Save Atlas7/6e03676da65bf467cb22d1ca42f20695 to your computer and use it in GitHub Desktop.
Save Atlas7/6e03676da65bf467cb22d1ca42f20695 to your computer and use it in GitHub Desktop.
Octave - find the min (or max) value of a Matrix, and the associated row and column

Whilst working through the many (Octave) coding assignment from Andrew Ng's Stanford Machine Learning course, a common problem that I have to solve revolves around this:

Given a Matrix A with m rows, and n columns find the mininum (or maximum) value and the associated row and column number

This article summarises my solution to this problem (which, hopefully this will also come in hadny to you!). Note that Octave index start from 1 (instead of 0).

Sample Matrix

Say we have a Matrix A that look like this:

octave:69> A = rand(3,4);
octave:70> A
A =

   0.128245   0.453621   0.205679   0.139355
   0.151691   0.431844   0.822562   0.044340
   0.736356   0.056389   0.893922   0.347978

Get Min Value

The minimum value may be found easily by doing this:

octave:71> min(min(A))
ans =  0.044340

(Note: the assiciated location is row 2, column 4 - if you scan through the matrix manually).

To find the associated row and column programmatically, just simply do this...

Find associated row

The associated row number is 2, as per followings:

octave:76> [minval, row] = min(min(A,[],2));
octave:77> row
row =  2

Find associated column

The associated column number is 4, as per followings:

octave:72> [minval, col] = min(min(A,[],1));
octave:75> col
col =  4

Do the same for max value

Simple, do the same but with max() instead of min().

Good luck!

@owenhust
Copy link

owenhust commented Aug 6, 2019

Typical way is to:
first, get min, or max from matrix, using min(matrix, [],1) for column min, min(matrix, [ ] , 2) for row min. the same to max.
and then use [i,j] = find(matrix == min or max) to find the indices
simple and effective.

just be careful when you have multiple min or max values, then you need to subset i, or j, as i, j returned will be vectors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment