Maximum Values of Matrix Subrows
1 view (last 30 days)
Show older comments
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 Comments
Answers (2)
David Goodmanson
on 28 Nov 2016
Edited: David Goodmanson
on 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 Comments
David Goodmanson
on 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
on 29 Nov 2016
Edited: David Goodmanson
on 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 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!