MATLAB: How to calculate the maximum of different parts of a vector without using a for loop

loopmaxsplitvectorized

Hi!
I have a vector H, which is separated in different events of known size, i.e. s=[2,5,7,2,…] and I want to find the maximum that corresponds to each event. How can I do it without using a for loop (I want to reduce the computational time)?
Using a for loop would be:
maxH(1) = max(H(1:s(1)));
for i=2:length(s)
maxH(i) = max(H( 1+sum(s(1:i-1)) : sum(s(1:i-1)) + s(i) ));
end
Thanks!
[EDITED, Jan, code formatted]

Best Answer

Although I don't recommend programming like this in MATLAB, sometimes writing out the logic out explicitly can make it run extremely fast. MATLAB has become very good at loops you know:
maxH = zeros(numel(s),1);
V = 1;
thismax = -inf;
thiss = s(1);
cnt = 1;
N = numel(H);
for n = 1:N
if cnt > thiss
maxH(V) = thismax;
thismax = H(n);
V = V+1;
cnt = 1;
thiss = s(V);
elseif H(n) > thismax
thismax = H(n);
end
cnt = cnt+1;
end
maxH(V) = thismax;