Summing/taking weighted average within a range for a table
2 views (last 30 days)
Show older comments
I am trying to find the sum of a certain column in my table within a certain range. So for example: 1-9, 10-18, 19-37, 38-90, ... 6330 - 6437 (the numbers are indices on the column im trying to use mathematical operations on). I have the starting points (1, 10, 19 ...) in one array and similarly the end points in another array.
How do I go about summing the terms? so summing 1st-9th, 10th-18th..?
Thanks
0 Comments
Answers (1)
Jon
on 19 Feb 2020
Edited: Jon
on 19 Feb 2020
Let's say you have a table called T, that has a column called x. To find, for example, the sum row 10 through 18 of variable x and store it in a variable called y, you would use
y = sum(T.x(10:18))
If you have a vector of start indices, call it iStart and a vector of end indices call them iEnd you could do something like
iSum = sort([iStart(:);iEnd(:)]); % (:) makes sure the vectors are concatenated as columns
y = sum(T.x(iSum))
or alternatively (maybe more efficient, avoiding the sort) you can interleave the start and stop indices
iSum = zeros(2*length(iStart),1);
iSum(1:2:end) = iStart
iSum(2:2:end) = iEnd
y = sum(T.x(iSum))
2 Comments
Jon
on 19 Feb 2020
You could easily do it in a little loop like:
% preallocate array to hold results
results = zeros(size(iStart));
% loop through the ranges computing sums of each range
for k = 1:length(results)
results(k,1) = sum(T.x(iStart(k):iEnd(k)));
end
It should also be possible to do this using grouping variables, and the "split-apply" work flow see https://www.mathworks.com/help/matlab/matlab_prog/grouping-variables-for-splitting-data.html
See Also
Categories
Find more on Particle & Nuclear Physics 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!