mrleopold
mrleopold

Reputation: 23

Matlab: How to sum up values in a certain range depending on entries in other columns

I'm pretty new to Matlab and not able to solve the following problem:

I've got three column vectors, "Day", "Name", "Values" each 300x1 and I need to sum up "Values" (cumulative) in a certain range which depend not only on the vector "Name" but also the vector "Day".

More precisely, I want to sum up the values in vector "Values" for each category (vector "Name") but only for a certain range (vector "Day"), let's say I want to sum up all the "Values" starting on "Day" 2, the "Result"-vector should look like (shortened example):

| Day | Name | Values | Result |
|-----|------|--------|------------|
| 1   | A    | 2      | 0          |
| 1   | C    | 9      | 0          |
| 1   | B    | 7      | 0          |
| 2   | D    | 1      | 1          |
| 2   | B    | 1      | 1          |
| 2   | A    | 3      | 3          |
| 2   | D    | 4      | 5          |
| 3   | D    | 9      | 14         |
| 3   | B    | 1      | 2          |
| 3   | C    | 3      | 3          |
| 3   | A    | 1      | 4          |
| 4   | D    | 3      | 17         |

Later on I would like to change the range, e.g. starting to sum up after "Day" 2, "Day" 3 and so on which would need to be adjustet for the starting "Day".

For my sum range starting on "Day" 2 I've created the following code but it does not work at all:

Result = zeros(size(Values));
a=unique(Name);
for k=1:length(a)
    for i = 1:length(Name)
        if Day(i) > 1
            Result(ismember(Name,a(k)))=cumsum(Values(ismember(Name,a(k))));
        end
    end
end

Is there anybody able to help? Many thanks in advance!

Upvotes: 2

Views: 554

Answers (1)

Cibin Joseph
Cibin Joseph

Reputation: 1273

I don't think the function ismember() is what you require here.

Try using another array to store the cumulative sums of each unique Name along with the function find() like so:

startDay = 2
NameList = unique(Name);
CumulSum = zeros(1, length(NameList));  % Array to store cumulative sum
Result = zeros(1, length(Name));

% For each row in the tabe
for row = 1:length(Name)

  % Check condition on Day
  if (Day(row) >= startDay)

    % Compute the cumulative sum
    % and store it in CumulSum array
    indx = find(NameList == Name(row));
    CumulSum(indx) = CumulSum(indx) + Values(row);

    % Use the cumulative sum as result for the row
    Result(row) = CumulSum(indx);

  end
end

Also, beware when using unique() on character arrays. You might want to ensure if the elements of Name are single characters.

Upvotes: 2

Related Questions