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).
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
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...
The associated row number is 2, as per followings:
octave:76> [minval, row] = min(min(A,[],2));
octave:77> row
row = 2
The associated column number is 4, as per followings:
octave:72> [minval, col] = min(min(A,[],1));
octave:75> col
col = 4
Simple, do the same but with max()
instead of min()
.
Good luck!
Hi, I ended up here while busy with the course. An apparently sparsely documented feature of the min and max functions is that they can return the index of the element they found as well as its value... so