Possibility to know the index of the max() value

조회 수: 2 (최근 30일)
André Pacheco
André Pacheco 2012년 12월 31일
Hello there,
I have a problem where I need to keep the maximum value and its position. In a while cycle I have one matrix that is created randomly, and I have to keep the maximum sum of the row in each iteration.
For example, I have one matrix (3 rows by 4 columns) that is p.e matrix a =
4 5 6 2
8 5 7 1
2 3 5 2
And another matrix that is (3 by 1) that keeps the sum of the matrix in some iteration p.e. matrix C=
17
21
12
Then I have a vector that keeps the max of the matrix C in order to build a graph of the evolution of the maximum value.
aux_vector=max(C);
I would like to keep the line that corresponds to the max of C, in this case the second line of the matrix a.
Thanks in advance.

채택된 답변

Walter Roberson
Walter Roberson 2012년 12월 31일
[aux_vector, aux_index] = max(C):
max_a = a(aux_index, :);
  댓글 수: 3
Walter Roberson
Walter Roberson 2012년 12월 31일
[aux_vector(iteration), aux_index] = max(C):
max_a(iteration,:) = a(aux_index, :);
André Pacheco
André Pacheco 2013년 1월 2일
It worked! thanks!

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

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 12월 31일
Try this code:
sumOfRows = sum(a, 2) % Your "C"
[maxValue, rowWithTheMax] = max(sumOfRows)
Here it is in a demo where we generate lots of random matrices "a" in a loop:
format compact;
numberOfRuns = 5;
% Initialize a matrix to keep track of the rows having
% the max sum at each iteration.
maxRows = zeros(numberOfRuns, 4); % One row for each run.
for k = 1 : 5
% Generate a matrix
if k == 1
% For the first run, use
% the example matrix the poster supplied.
a = [...
4 5 6 2
8 5 7 1
2 3 5 2]
else
% Subsequent runs use a random matrix.
a = randi(9, [3 4])
end
sumOfRows = sum(a, 2) % Your "C"
[maxValue, rowWithTheMax] = max(sumOfRows)
% Store this row in an array that depends on the run.
% In other words, store the 4 values from that row of "a".
maxRows(k, :) = a(rowWithTheMax, :)
end
Hopefully it's commented well enough to explain what's going on.
  댓글 수: 2
Image Analyst
Image Analyst 2012년 12월 31일
Actually I noticed that this is virtually the same as Walter's. I didn't realize at first because I didn't see sum() in his code.
André Pacheco
André Pacheco 2013년 1월 2일
I've tried and it worked! Although i used the first answers but it is the same as u made. Thanks !

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by