MATLAB: Row sums by vector indices without for loop

for loopmatrix arraysum

Best illustrated by example
M=rand(5,10);
s=[1 3; 5 8; 9 10];
for i=1:size(s,1)
sm(:,i)=sum(M(:,s(i,1):s(i,2)),2);
end
Is there a one-liner or short-cut for the for loop? I do not know how large M or s is ahead of time, or their values. Above code shown only for illustration of problem trying to solve.
Thanks!
edit: Corrected typo of 'm' in for-loop to 'M'

Best Answer

If your accuracy requirements are not high and your values are not extreme, you can use cumsum(), after which it becomes the difference of the cumsum indexed at two positions -- a transformation that gets around the problem that your indices do not always designate the same number of elements to be summed per row.
If I recall collectly, Bruno, and Matt Fig, both have posted non-cumsum() versions of this task in the past (it has come up before in cssm discussions.)