Maximum Values of Matrix Subrows

1 visualizzazione (ultimi 30 giorni)
ADD
ADD il 28 Nov 2016
Modificato: David Goodmanson il 29 Nov 2016
Hello,
What is a smart way (without loops) to find maximum values of matrix sub rows, with variable start and end subscripts. E.g., for a NxN matrix, I want to get a Nx1 vector of maximum values for each matrix sub row, with variable start and end subscripts.
Many thanks!

Risposte (2)

David Goodmanson
David Goodmanson il 28 Nov 2016
Modificato: David Goodmanson il 28 Nov 2016
ADD, if I understand the question correctly, for matrix M this would be a = max(M,[ ],2) where the 2 is for max along rows instead of along columns.
  2 Commenti
ADD
ADD il 28 Nov 2016
David, The problem is that I want to find maximum values in subsets of rows. So for an NxN matrix M, I want max(M(i,a(i):b(i))), for i = 1,...,N, where i is the row and a(i) and b(i) are starting and ending cols that define the range within each row. I have a very large matrix and looking for a way to do this without doing a loop over i.
David Goodmanson
David Goodmanson il 29 Nov 2016
I see I didn't understand the question and it will be interesting to see if someone finds a way.

Accedi per commentare.


David Goodmanson
David Goodmanson il 29 Nov 2016
Modificato: David Goodmanson il 29 Nov 2016
ADD, ok here is one way to do this. It does modify the matrix in order to get the answer, so in this script file M gets changed and I suppose in a function you need more memory for a copy, I'n not quite sure. There are probably better ways to do this, depending for one thing on how long the selected rows are compared to N, on average.
I don't know how big your matrix is but not counting creating the initial matrix, for a 20k x 20k matrix of doubles this took a little less than 7 sec. on my PC.
However, it only took 3 sec. to do the same thing with a for loop. The slow way is faster. Negative progress! Hopefully someone will weigh in with a more efficient method.
% find max of M(k,a:b) by row, for an NxN matrix M
% a is a vector of row indices
% b is a vector of row indices, a<=b
Q = zeros(N,N+1,'int8'); % includes helper column for b index
aa = sub2ind([N,N+1],1:N,a );
bb = sub2ind([N,N+1],1:N,b+1);
Q(aa) = 1;
Q(bb) = -1;
Q = cumsum(Q,2); % mark elements to save
Q = Q(:,1:end-1); % take away helper column
M(~Q) = nan; % nans are ignored by max
rowmax_a_b = max(M,[ ],2);

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by