Possibility to know the index of the max() value

2 visualizaciones (últimos 30 días)
André Pacheco
André Pacheco el 31 de Dic. de 2012
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.

Respuesta aceptada

Walter Roberson
Walter Roberson el 31 de Dic. de 2012
[aux_vector, aux_index] = max(C):
max_a = a(aux_index, :);
  3 comentarios
Walter Roberson
Walter Roberson el 31 de Dic. de 2012
[aux_vector(iteration), aux_index] = max(C):
max_a(iteration,:) = a(aux_index, :);
André Pacheco
André Pacheco el 2 de En. de 2013
It worked! thanks!

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 31 de Dic. de 2012
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 comentarios
Image Analyst
Image Analyst el 31 de Dic. de 2012
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 el 2 de En. de 2013
I've tried and it worked! Although i used the first answers but it is the same as u made. Thanks !

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by