Possibility to know the index of the max() value

2 次查看(过去 30 天)
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, :);

请先登录,再进行评论。

更多回答(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