Skip to content

Instantly share code, notes, and snippets.

@Bladefidz
Forked from Atlas7/octave_tip.md
Created March 1, 2018 09:22
Show Gist options
  • Save Bladefidz/5db4adbbad425cd023b9c312dadd68ad to your computer and use it in GitHub Desktop.
Save Bladefidz/5db4adbbad425cd023b9c312dadd68ad 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!

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