# Find the maximum value and its location from a matrix using two nested loops

14 views (last 30 days)
Kantosa on 8 Dec 2013
Edited: Alexandra Vaupotic on 8 Feb 2021
Hi,
Right now I have this matrix K
K =
-3 -8 6 -3 -8 6 9 24 -18
-5 10 -9 -5 10 -9 15 -30 27
8 4 9 8 4 9 -24 -12 -27
-9 -24 18 12 32 -24 3 8 -6
-15 30 -27 20 -40 36 5 -10 9
24 12 27 -32 -16 -36 -8 -4 -9
9 24 -18 -15 -40 30 0 0 0
15 -30 27 -25 50 -45 0 0 0
-24 -12 -27 40 20 45 0 0 0
I wonder how I can use two nested loops to find the maximum number and its location from this matrix.
It would be great if anyone can help me with this
Thank you very much :)
##### 1 CommentShow -1 older commentsHide -1 older comments
sixwwwwww on 8 Dec 2013
Is it homework?

Sign in to comment.

### Accepted Answer

sixwwwwww on 8 Dec 2013
Edited: sixwwwwww on 8 Dec 2013
you can do it as follow:
MaxValue = -Inf;
row = 0;
column = 0;
for i = 1:size(K, 1)
for j = 1:size(K, 2)
if K(i, j) > MaxValue
MaxValue = K(i, j);
row = i;
column = j;
end
end
end
##### 6 CommentsShow 4 older commentsHide 4 older comments
Image Analyst on 8 Dec 2013
But you didn't ask for other ways - you rigidly specified the way. The other, more MATLAB-ish way would be to use the max() function. Look at the two arguments it returns. You might also find ind2sub() helpful,
Alexandra Vaupotic on 8 Feb 2021
Edited: Alexandra Vaupotic on 8 Feb 2021
How could you make this a function with an output of the Max value?

Sign in to comment.

### More Answers (1)

Khalid Mojallid on 26 Mar 2019
MaxValue = -Inf;
row = 0;
column = 0;
for i = 1:size(K, 1)
for j = 1:size(K, 2)
if K(i, j) > MaxValue
MaxValue = K(i, j);
row = i;
column = j;
end
end
end
##### 1 CommentShow -1 older commentsHide -1 older comments
Nathan Blais on 3 Oct 2019
I'm guessing K would be the vector we are trying to find the max value for?

Sign in to comment.

### Categories

Find more on Mathematics in Help Center and File Exchange

### Tags

No tags entered yet.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!