Maximum Values of Matrix Subrows
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponses (2)
David Goodmanson
le 28 Nov 2016
Modifié(e) : David Goodmanson
le 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 commentaires
David Goodmanson
le 29 Nov 2016
I see I didn't understand the question and it will be interesting to see if someone finds a way.
David Goodmanson
le 29 Nov 2016
Modifié(e) : David Goodmanson
le 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);
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!