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

조회 수: 41 (최근 30일)
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 :)

채택된 답변

sixwwwwww
sixwwwwww 2013년 12월 8일
편집: sixwwwwww 2013년 12월 8일
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
Image Analyst
Image Analyst 2013년 12월 8일
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
Alexandra Vaupotic 2021년 2월 8일
편집: Alexandra Vaupotic 2021년 2월 8일
How could you make this a function with an output of the Max value?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Khalid Mojallid
Khalid Mojallid 2019년 3월 26일
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

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by