Possibility to know the index of the max() value

1 回表示 (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by