Summing/taking weighted average within a range for a table

2 vues (au cours des 30 derniers jours)
ak
ak le 19 Fév 2020
Commenté : Jon le 19 Fév 2020
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

Réponses (1)

Jon
Jon le 19 Fév 2020
Modifié(e) : Jon le 19 Fév 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 commentaires
ak
ak le 19 Fév 2020
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
Jon le 19 Fév 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by