Summing/taking weighted average within a range for a table

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

답변 (1개)

Jon
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

Hi thanks for the response.
An issue I am having is that I keep getting 1 summation, but I am trying to get a bunch of summations:
Say my table is what I have below, I am trying to get the summation of: 1-3,4-9,10-13,14-21 in 1 array output.
I have start points (1,4,10,14) in 1 array and the end points (3,9,13,21) in another array,
10.00
10.00
9.00
10.00
10.00
10.00
10.00
10.00
9.00
10.00
9.00
10.00
10.00
10.00
10.00
10.00
9.00
10.00
10.00
9.00
10.00
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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

ak
2020년 2월 19일

댓글:

Jon
2020년 2월 19일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by