MATLAB: How to find the position of the max positive value in a matrix row by row

maxpositivevalue

Hey my Matlab friends:
I have a maxtrix (176*250), but for simplicity, I will use a 4*4 matrix to ask questions,
suppose I have a matrix A
A = [0 0 0 0; -15 -15 -15 -15; -65 -18 3 17; -1 3 4 18]
I must to start in row 1, but isn´t maximum in there, now I must follow in row 2 but isn´t maximum in there, Now in row 3 there are nonzero and positive values. My question is how to ask matlab return me a value that can tell me the location of this max value of the first row found with nonzero and positive values (row 3 column 4)?
Thanks!!!
YH

Best Answer

Try this:
A = [0 0 0 0; -15 -15 -15 -15; -65 -18 3 17; -1 3 4 18]
goodRows = find(any(A>0, 2))
firstRow = goodRows(1)
[firstMaxValue, columnOfMax] = max(A(firstRow, :))
fprintf('The first row that has at least one positive value is %d.\n', firstRow);
fprintf('The max of that row (#%d) is located in column %d.\n', firstRow, columnOfMax);
fprintf('The value there is A(%d, %d) = %f.\n', firstRow, columnOfMax, A(firstRow, columnOfMax));
You'll see this in the command window:
A =
0 0 0 0
-15 -15 -15 -15
-65 -18 3 17
-1 3 4 18
goodRows =
3
4
firstRow =
3
firstMaxValue =
17
columnOfMax =
4
The first row that has at least one positive value is 3.
The max of that row (#3) is located in column 4.
The value there is A(3, 4) = 17.000000.