# Summing/taking weighted average within a range for a table

4 ビュー (過去 30 日間)
ak 2020 年 2 月 19 日
コメント済み: Jon 2020 年 2 月 19 日
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 件のコメント

サインイン to comment.

### 回答 (1 件)

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 件のコメント

ak 2020 年 2 月 19 日
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
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

サインイン to comment.

サインイン してこの質問に回答します。