Summing/taking weighted average within a range for a table
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Jon
2020-2-19
编辑:Jon
2020-2-19
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 个评论
Jon
2020-2-19
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Particle & Nuclear Physics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!